如何使用字符串作为属性名称从嵌套对象组中找到对象属性值?
问题描述:
我有一个嵌套的对象集,即一些属性是自定义对象。我希望在属性名称中使用字符串来获取层次结构组中的对象属性值,并使用某种形式的“find”方法来扫描层次结构以查找具有匹配名称的属性,并获取其值。如何使用字符串作为属性名称从嵌套对象组中找到对象属性值?
这是可能的,如果是的话如何?
非常感谢。
编辑
类定义可能是伪代码:
Class Car
Public Window myWindow()
Public Door myDoor()
Class Window
Public Shape()
Class Door
Public Material()
Car myCar = new Car()
myCar.myWindow.Shape ="Round"
myDoor.Material = "Metal"
都有点做作,但通过使用魔法字符串“形”我能“找到”的“形”属性的值在某种形式的查找函数中,从顶层对象开始。 ie:
string myResult = myCar.FindPropertyValue("Shape")
希望myResult =“Round”。
这就是我所追求的。
谢谢。
答
根据您在问题中显示的类,您需要递归调用来迭代对象属性。怎么样东西,你可以重复使用:
object GetValueFromClassProperty(string propname, object instance)
{
var type = instance.GetType();
foreach (var property in type.GetProperties())
{
var value = property.GetValue(instance, null);
if (property.PropertyType.FullName != "System.String"
&& !property.PropertyType.IsPrimitive)
{
return GetValueFromClassProperty(propname, value);
}
else if (property.Name == propname)
{
return value;
}
}
// if you reach this point then the property does not exists
return null;
}
propname
是您正在搜索的属性。您可以使用是这样的:
var val = GetValueFromClassProperty("Shape", myCar);
答
是的,这是可能的。
public static Object GetPropValue(this 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;
}
public static T GetPropValue<T>(this Object obj, String name) {
Object retval = GetPropValue(obj, name);
if (retval == null) { return default(T); }
// throws InvalidCastException if types are incompatible
return (T) retval;
}
要使用此:
DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
看到这个link,供大家参考。
试图获得更具体的使用 –
反射和'PropertyInfo' http://stackoverflow.com/questions/1355090/using-propertyinfo-getvalue –
只是添加了例如编辑。这是否改变了思考的答案?应对嵌套很重要。 – SamJolly