如何使用字符串作为属性名从嵌套的对象组中查找对象属性值?

Sam*_*lly 5 c# asp.net-mvc-3

我有一组嵌套的对象,即一些属性是自定义对象.我想在层次结构组中使用字符串作为属性名称来获取对象属性值,并使用某种形式的"查找"方法来扫描层次结构以查找具有匹配名称的属性,并获取其值.

这有可能吗?如果可以的话怎么样?

非常感谢.

编辑

类定义可以是伪代码:

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"
Run Code Online (Sandbox Code Playgroud)

所有人都有点做作,但是我可以通过在顶层对象的某种形式的find函数中使用魔术字符串"Shape"来"找到""Shape"属性的值.即:

string myResult = myCar.FindPropertyValue("Shape")
Run Code Online (Sandbox Code Playgroud)

希望myResult ="Round".

这就是我所追求的.

谢谢.

von*_* v. 9

根据您在问题中显示的类,您需要通过递归调用来迭代对象属性.你可以重用的东西怎么样:

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;
}
Run Code Online (Sandbox Code Playgroud)

propname是您要搜索的属性.你可以使用是这样的:

var val = GetValueFromClassProperty("Shape", myCar );
Run Code Online (Sandbox Code Playgroud)