C# 使用反射将可为null的属性复制到不可为null的版本
我正在编写代码,使用反射将一个对象转换为另一个对象 这项工作正在进行中,但我认为可以归结为以下几点:我们相信两处房产的类型相同:C# 使用反射将可为null的属性复制到不可为null的版本,c#,.net,reflection,C#,.net,Reflection,我正在编写代码,使用反射将一个对象转换为另一个对象 这项工作正在进行中,但我认为可以归结为以下几点:我们相信两处房产的类型相同: private void CopyPropertyValue(object source, string sourcePropertyName, object target, string targetPropertyName) { PropertyInfo sourceProperty = source.GetType().GetPr
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));
}
但是,我还有一个问题,源类型可能为空,而目标类型可能不为空。e、 gNullable
=>int
。在这种情况下,我需要确保它仍然有效,并执行一些合理的行为,例如NOP或设置该类型的默认值
这可能是什么样子?鉴于
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);
}
}
Nullable.getUnderlineType(targetProperty)
对我来说似乎不好。@JeppeStigNielsen:对不起,我是想用.PropertyType
。已修复。我们真的需要这两种类型吗,targetProperty.PropertyType.IsValueType&&Nullable.GetUnderlineingType(targetProperty.PropertyType)!=空值
?编辑:啊,现在我明白了,你说它是一种值类型,而不是特殊的值类型Nullable
。一切都很好。@JeppeStigNielsen:Whoops-它实际上应该是==null
,在这一点上是的,我们两者都需要。@Mr.Boy:那么我假设您想将值设置为null,这就是我展示的代码将要做的。也许我只是疯了,但知道潜在的问题,它似乎可以以更好的方式解决表达式树,我不遵循,请随时提供答案!我的意思是,你可以解释你想解决什么,而不是你想如何解决我们不知道的问题……不,我的意思是,在这里我不理解你所说的“表达式树”。这个场景是我有两个不相关的类,但是存在一个映射,例如X.name=>Y.shortName,等等,我想在运行时而不是编译时定义这个转换映射。基本上类似于使用XSLT,但用于C#对象。那么MapPropertyTo(x=>x.name,y=>y.shortName)
呢?