使用Reflection将Nullable属性复制到非Nullable版本

时间:2016-07-28 13:46:39

标签: c# .net reflection

我正在编写代码,使用反射将一个对象转换为另一个对象......

它正在进行中,但我认为可归结为以下我们相信这两个属性具有相同的类型:

    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));
    }

然而我还有一个问题,即源类型可能是Nullable而目标类型不是。例如Nullable<int> =&gt; int。在这种情况下,我需要确保它仍然有效并且执行一些明智的行为,例如NOP或设置该类型的默认值。

这看起来像什么?

1 个答案:

答案 0 :(得分:7)

鉴于GetValue返回盒装表示,它将是可空类型的空值的空引用,它很容易检测,然后处理你想:

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);
    }
}