c# - Copy a Nullable property to a non-Nullable version using Reflection -
i writing code transform 1 object using reflection...
it's in progress think boil down following trust both properties have same type:
private void copypropertyvalue(object source, string sourcepropertyname, object target, string targetpropertyname) { propertyinfo sourceproperty = source.gettype().getproperty(sourcepropertyname); propertyinfo targetproperty = target.gettype().getproperty(targetpropertyname); targetproperty.setvalue(target, sourceproperty.getvalue(source)); }
however have additional issue source type might nullable , target type not. e.g nullable<int>
=> int
. in case need make sure still works , sensible behaviour performed e.g. nop or set default value type.
what might like?
given getvalue
returns boxed representation, null reference null value of nullable type, it's easy detect , handle want:
private void copypropertyvalue( object source, string sourcepropertyname, object target, string targetpropertyname) { propertyinfo sourceproperty = source.gettype().getproperty(sourcepropertyname); propertyinfo targetproperty = target.gettype().getproperty(targetpropertyname); object value = sourceproperty.getvalue(source); if (value == null && targetproperty.propertytype.isvaluetype && nullable.getunderlyingtype(targetproperty.propertytype) == null) { // okay, trying copy null value non-nullable type. // whatever want here } else { targetproperty.setvalue(target, value); } }
Comments
Post a Comment