我正在编写代码以使用反射将一个对象转换为另一个对象......
它正在进行中,但我认为它可以归结为以下内容,我们相信这两个属性具有相同的类型:
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我还有一个额外的问题,即源类型可能为 Nullable,而目标类型则不是。例如Nullable<int>
=> int
。在这种情况下,我需要确保它仍然有效并且执行一些明智的行为,例如NOP 或设置该类型的默认值。
这看起来会是什么样子?
鉴于GetValue
返回一个boxed表示,这将是可空类型的空值的空引用,很容易检测到,然后根据需要进行处理:
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)