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

6

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

这是否可行,如果可以,怎么做?

非常感谢。

编辑

类定义可能是伪代码:

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")

希望我的结果 = "Round"。
这就是我所追求的。
谢谢。

1
尝试变得更具体。 - Dave Alperovich
1
使用反射和PropertyInfo:https://dev59.com/FXM_5IYBdhLWcg3wfTS7 - Julián Urbano
刚刚添加了一个带有示例的编辑。这会改变反射答案吗?处理嵌套很重要。 - SamJolly
2个回答

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;
}

propname 是您要搜索的属性。您可以像这样使用它:

var val = GetValueFromClassProperty("Shape", myCar );

4
是的,这是可能的。
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");

请参考此链接,了解相关的IT技术。


谢谢。这是否意味着我必须在“名称”中指定对象层次结构?我希望只需指定“形状”,它就会沿着对象层次结构向下搜索以找到第一个名称匹配项。 - SamJolly
是的。请注意,类上不能有重复的属性,因此如果您对层次结构持怀疑态度,这不会成为问题。 - roybalderama

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接