How to use C# Reflection to set properties and fields with generic code? -
my code wants iterate dictionary contains both fieldinfo , propertyinfo of type, , use map values 1 object another. 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]; // now, match datatypes directly if (datatypesmatch(source, target)) { var sourcevalue = sourceproperty.getvalue(source); try { targetproperty.setvalue(target, sourcevalue); } catch (targetexception e) { log.errorformat("unable set value {0} property={1}, ex={2}", sourcevalue, targetproperty, e); } } } }
the problems above are: 1) datatypesmatch()
function requires 2 different method signatures 1 fieldinfo
, 1 propertyinfo
(and check type of each , cast appropriately dispatch correct function). because check field data type uses fieldinfo.fieldtype
while data type property uses propertyinfo.propertytype
.
2) though both fieldinfo
, propertyinfo
have setvalue
, getvalue
methods, not derive common parent class, again requires cast. (maybe dynamic take care of problem?)
is there solution allows treating these 2 types of memberinfo objects generically check datatype , get/setvalue?
why not modify method take 2 arguments of type type, , pass fieldinfo.fieldtype
, propertyinfo.propertytype
accordingly?
Comments
Post a Comment