2012-01-25 38 views
1

我試圖從一個對象複製一些屬性值到另一個(兩個對象實現IVenue,但對象B需要有一些值動態刪除)。想避免像很多代碼:爲什麼Reflection的SetValue會引發異常?

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 as source.GetValue(v,null)返回期望值。

任何人都可以解釋我做錯了什麼?如果這將是一個更合適的解決方案,請隨意提出一個完全可選的方法。

回答

4

您在SetValue上的第一個參數不正確 - 它試圖在PropertyInfo上設置屬性

你大概的意思是:

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

飛碟雙向先生,我可以吻你(但我不會)。 – Simon

相關問題