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

发布于 2024-12-29 00:54:23 字数 932 浏览 2 评论 0原文

我正在尝试将一些属性值从一个对象复制到另一个对象(两个对象都实现 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我的影子我的梦 2025-01-05 00:54:23

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

你的意思可能是:

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

Your first argument on SetValue is incorrect - it's try to set the property on the PropertyInfo.

You probably meant:

 p.SetValue(this, source.GetValue(v, null), null);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文