如何使用字符串作为属性名称从嵌套对象组中找到对象属性值? [英] How to find an object property value from a nested objected group using a string as the property name?
问题描述
我有一组嵌套的对象,即某些属性是自定义对象.我想使用字符串作为属性名称来获取层次结构组中的对象属性值,并使用某种形式的查找"方法来扫描层次结构以查找具有匹配名称的属性,并获取其值.
I have a nested set of objects ie some properties are custom objects. I would like to get a object property value within the hierarchy group using a string for the property name, and some form of "find" method to scan the hierarchy to find a property with matching name, and get its value.
这有可能吗?
非常感谢.
编辑
类定义可能是伪代码:
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"
有点作弊,但是我可以通过某种形式的find函数,使用魔术字符串"Shape",从顶部对象开始,找到""Shape"属性的值. 即:
All a little contrived, but could I "find" the value of the "Shape" property by using the magic string "Shape" in some form of find function, starting from the top object. ie:
string myResult = myCar.FindPropertyValue("Shape")
希望myResult ="Round".
Hopefully myResult = "Round".
这就是我的追求.
谢谢.
推荐答案
基于您在问题中显示的类,您将需要递归调用来迭代对象属性.可以重复使用的东西怎么样:
Based on classes you showed in your question, you would need a recursive call to iterate your object properties. How about something you can reuse:
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
是您要搜索的属性.您可以这样使用:
propname
is the property you are searching for. You can use is like this:
var val = GetValueFromClassProperty("Shape", myCar );
这篇关于如何使用字符串作为属性名称从嵌套对象组中找到对象属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!