gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:15 25 4
gpt4 key购买 nike

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

关于c# - 为什么 Reflection 的 SetValue 会抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9002045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com