Skip to main content
 首页 » 编程设计

c#之为什么 Reflection 的 SetValue 会抛出异常

2024年02月23日18txw1958

我正在尝试将一些属性值从一个对象复制到另一个对象(两个对象都实现了 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); 
    } 
} 

但是我收到错误:

"Object does not match target type"

两个属性都是int类型,声明为:

public int ID { get; set; } 

问题似乎在于 p.SetValue,因为 source.GetValue(v,null) 返回预期值。

谁能解释一下我做错了什么?如果这是更合适的解决方案,请随意提出一个完全替代的方法。

请您参考如下方法:

SetValue 上的第一个参数不正确 - 它试图在 PropertyInfo 上设置属性。

你的意思可能是:

 p.SetValue(this, source.GetValue(v, null), null);