我需要獲取和設置屬性值動態設置屬性值
我讀這Get property value from string using reflection in C#
,做了下面的代碼用於獲取的值
public Object GetPropValue(Object obj, String name) {
foreach (String part in name.Split('.')) {
if (obj == null) { return null; }
Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }
obj = info.GetValue(obj, null);
}
return obj;
}
現在我需要設置值到具有相同屬性名稱的其他對象
Employee emp1=new Employee();
var city=GetPropValue(emp1, "Address.City");
Need to set this city to other employee. Here Address is other class
emp1.GetType().GetProperty("Address.City").SetValue(emp2,city,null) //always sets null
但它是n ot設置。我怎樣才能使一個通用的setter方法使這個工作簡單?
即使我想這樣也。但它總是設置爲空。我們如何設置嵌套的對象屬性? – Billa 2013-05-07 11:44:07
'city'是否有值或是'city'' null'?你有沒有嘗試設置一個斷點? – 2013-05-07 12:14:34