我需要获取和设置属性值动态设置属性值
我读这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