2016-07-28 74 views
2

我写代码,一个对象转换到另一个使用反射...可空属性复制到一个非空的版本使用反射

这是在进步,但我认为这将归结到我们相信以下这两个属性具有相同的类型:

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<int> =>int。在这种情况下,我需要确保它仍然有效,并执行了一些合理的行为,例如NOP或设置该类型的默认值。

可能这是什么样的?

+0

也许我只是疯狂,但知道它似乎是它可以以更好的方式来解决表达式树的根本问题 –

+0

我不明白,请随时提供一个答案! –

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

'Nullable.GetUnderlyingType(targetProperty)'对我来说似乎不好。 –

+0

@JeppeStigNielsen:对不起,本来打算使用'.PropertyType'。固定。 –

+0

我们真的需要两个,'targetProperty.PropertyType.IsValueType && Nullable.GetUnderlyingType(targetProperty.PropertyType)!= null'? ___编辑:___啊,现在我明白了,你说它是一个值类型_and_它不是特殊值类型'Nullable <>'。一切都很好。 –

相关问题