【问题标题】:How to find an object property value from a nested objected group using a string as the property name?如何使用字符串作为属性名称从嵌套对象组中查找对象属性值?
【发布时间】:2016-12-06 10:02:57
【问题描述】:

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

这可能吗?如果可以,怎么做?

非常感谢。

编辑

类定义可能是伪代码:

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

这就是我所追求的。

谢谢。

【问题讨论】:

标签: c# asp.net-mvc-3


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    是的,这是可能的。

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

    请参阅此link 以供参考。

    【讨论】:

    • 谢谢。这是否意味着我必须在“名称”中指定对象层次结构。我希望只指定“形状”,它会向下搜索对象层次结构以找到第一个匹配的名称。
    • 是的。请注意,您不能在类上拥有重复的属性,因此如果您对层次结构持怀疑态度,这不会成为问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 2012-02-21
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多