本文介绍了使用反射将 Nullable 属性复制到非 Nullable 版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

这会是什么样子?

推荐答案

鉴于 GetValue 返回一个 boxed 表示,这将是一个空值引用可以为 null 的类型,很容易检测到,然后根据需要进行处理:

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

这篇关于使用反射将 Nullable 属性复制到非 Nullable 版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:39
查看更多