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

标签 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"

有点做作,但我可以通过在某种形式的查找函数中使用魔术字符串“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/

相关文章:

c# - 按字典顺序排序的字符串列表列表

c# - 序列化基类列表的 XML

asp.net - 使用 MySql 和 MVC 3 上的成员(member)资格向注册表单添加更多字段

asp.net-mvc - ASP.NET MVC3 在 Windows 8 中不工作

asp.net-mvc - 将 updatemodel 与 EF4.3.1 一起使用时出现 InvalidOperationException

c# - 计算执行函数所需时间的问题

c# - XNA - GraphicsDevice 初始化困惑

c# - 将 supportedRuntime 嵌入到 exe 文件中

javascript - ASP.NET MVC 部分 View ajax 帖子?

c# - 如何创建 2 个相关的下拉列表