我有一组嵌套的对象,即一些属性是自定义对象。我想使用属性名称的字符串在层次结构组中获取对象属性值,并使用某种形式的“查找”方法来扫描层次结构以查找具有匹配名称的属性,并获取其值。
这可能吗?如果可能的话如何?
非常感谢。
编辑
类定义可能是伪代码:
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"
有点做作,但我可以通过在某种形式的查找函数中使用魔术字符串“Shape”从顶部对象开始“找到”“Shape”属性的值。 即:
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 );
关于c# - 如何使用字符串作为属性名称从嵌套对象组中查找对象属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027366/