[英]Why does Reflection's SetValue throw an exception?
我正在尝试将一些属性值从一个对象复制到另一个对象(两个对象都实现IVenue,但是对象b需要动态删除一些值)。 想要避免很多代码,例如:
a.Property1 = b.Property1;
a.Property2 = b.Property2;
etc
我正在尝试使用Reflection来循环属性并复制:
public VenueContract(TVDData.Interfaces.IVenue v, List<TVDData.APIClientPermittedFields> permittedFields)
{
PropertyInfo[] Properties = this.GetType().GetProperties( BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo p in Properties)
{
PropertyInfo source = v.GetType().GetProperty(p.Name, BindingFlags.Public | BindingFlags.Instance);
p.SetValue (p, source.GetValue(v,null),null);
}
}
但是我收到错误:
“对象与目标类型不匹配”
这两个属性均为int类型,声明为:
public int ID { get; set; }
问题似乎出在p.SetValue作为source.GetValue(v,null)返回期望值。
谁能解释我在做什么错? 如果这是一个更合适的解决方案,请随意提出一种完全替代的方法。
您在SetValue
上的第一个参数不正确-尝试在PropertyInfo
上设置PropertyInfo
。
您可能的意思是:
p.SetValue(this, source.GetValue(v, null), null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.