Copy a Nullable property to a non-Nullable version using Reflection

别来无恙 提交于 2020-01-15 03:49:09

问题


I am writing code to transform one object to another using reflection...

It's in progress but I think it would boil down to the following where we trust both properties have the 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 I have the additional issue that the source type might be Nullable and the target type not. e.g Nullable<int> => int. In this case I need to make sure it still works and some sensible behaviour is performed e.g. NOP or set the default value for that type.

What might this look like?


回答1:


Given that GetValue returns a boxed representation, which will be a null reference for a null value of the nullable type, it's easy to detect and then handle however you 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 to copy a null value into a non-nullable type.
        // Do whatever you want here
    }
    else
    {
        targetProperty.SetValue(target, value);
    }
}


来源:https://stackoverflow.com/questions/38638346/copy-a-nullable-property-to-a-non-nullable-version-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!