簡體   English   中英

為什么反射的SetValue會引發異常?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM