How to find the value of an object property from a nested group of objects using a string as the property name?

I have a nested set of objects, i.e. some properties are custom objects. I would like to get the value of a property of an object in a hierarchy group using a string for the name of the property, and some form of the “find” method to scan the hierarchy to find the property with the corresponding name and get its value.

Is this possible, and if so, how?

Many thanks.

EDIT

The class definition may be in pseudocode:

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"

Everything is a little far-fetched, but can I "find" the value of the "Shape" property using the "Shape" magic string in some form of search function, starting from the top object. i.e:

string myResult = myCar.FindPropertyValue("Shape")

I hope myResult = "Round".

, .

.

+5
2

, , . , :

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

, .

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

. .

+4

All Articles