为什么Reflection的SetValue会抛出异常?
我正在尝试将一些属性值从一个对象复制到另一个对象(两个对象都实现 IVenue,但对象 b 需要动态删除一些值)。想要避免很多代码,例如:
a.Property1 = b.Property1;
a.Property2 = b.Property2;
etc
我正在尝试使用反射来循环属性并复制:
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) 返回预期值。
谁能解释我做错了什么?如果这是一个更合适的解决方案,请随意建议一种完全替代的方法。
I am trying to copy some property values from one object to another (both objects implement IVenue, but object b needs to have some values removed dynamically). Wanting to avoid a lot of code like:
a.Property1 = b.Property1;
a.Property2 = b.Property2;
etc
I am attempting to use Reflection to loop the properties and copy across:
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);
}
}
However I receive the error:
"Object does not match target type"
Both properties are type int, declared as:
public int ID { get; set; }
The problem appears to lie in p.SetValue as source.GetValue(v,null) returns the expected value.
Can anyone explain what I am doing wrong? Feel free to suggest a completely alternative approach if that would be a more appropriate solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SetValue
上的第一个参数不正确 - 它尝试在PropertyInfo
上设置属性。你的意思可能是:
Your first argument on
SetValue
is incorrect - it's try to set the property on thePropertyInfo
.You probably meant: