My code wants to iterate a Dictionary that contains both FieldInfo and PropertyInfo of a type, and use that to map the values from one object to another. For example:
public static void MapFieldsAndProperties(object source, object target)
{
Dictionary<string, MemberInfo> target_properties = ClassUtils.GetPropertiesAndFields(target);
Dictionary<string, MemberInfo> source_properties = ClassUtils.GetMatchingPropertiesAndFields(target_properties.Keys, source);
foreach (var entry in source_properties)
{
var sourceProperty = entry.Value;
var targetProperty = target_properties[entry.Key];
// for now, match datatypes directly
if (dataTypesMatch(source, target))
{
var sourceValue = sourceProperty.GetValue(source);
try
{
targetProperty.SetValue(target, sourceValue);
}
catch (TargetException e)
{
LOG.ErrorFormat("unable to set value {0} for property={1}, ex={2}", sourceValue, targetProperty, e);
}
}
}
}
The problems with the above are: 1) The dataTypesMatch()
function requires 2 different method signatures one for FieldInfo
and one for PropertyInfo
(and then to check the type of each and cast appropriately to dispatch to correct function). This is because to check Field data type uses FieldInfo.FieldType
while data type for Property uses PropertyInfo.PropertyType
.
2) Even though both FieldInfo
and PropertyInfo
have SetValue
and GetValue
methods, they do not derive from a common parent class, so it again requires a cast. (Maybe Dynamic would take care of this problem?)
Is there a solution which allows treating these 2 types of MemberInfo objects generically to check DataType and to Get/SetValue?
Aucun commentaire:
Enregistrer un commentaire