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

Mr.*_*Boy 2 .net c# 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));
    }
Run Code Online (Sandbox Code Playgroud)

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

这看起来像什么?

Jon*_*eet 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);
    }
}
Run Code Online (Sandbox Code Playgroud)