简体   繁体   English

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

[英]Copy a Nullable property to a non-Nullable version using Reflection

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. 但是我还有一个额外的问题,即源类型可能是Nullable而目标类型不是。 eg Nullable<int> => int . 例如Nullable<int> => int In this case I need to make sure it still works and some sensible behaviour is performed eg NOP or set the default value for that type. 在这种情况下,我需要确保它仍然有效,并执行一些明智的行为,例如NOP或设置该类型的默认值。

What might this look like? 这看起来像什么?

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: 鉴于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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM