I have a nested set of objects ie some properties are custom objects. I would like to get a object property value within the hierarchy group using a string for the property name, and some form of "find" method to scan the hierarchy to find a property with matching name, and get its value.
Is this possible and if so how?
Many thanks.
EDIT
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"
All a little contrived, but could I "find" the value of the "Shape" property by using the magic string "Shape" in some form of find function, starting from the top object.
ie:
string myResult = myCar.FindPropertyValue("Shape")
Hopefully myResult = "Round".
This is what I am after.
Thanks.
Based on classes you showed in your question, you would need a recursive call to iterate your object properties. How about something you can reuse:
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
is the property you are searching for. You can use is like this:
var val = GetValueFromClassProperty("Shape", myCar );
Yes, this is possible.
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;
}
To use this:
DateTime now = DateTime.Now;
int min = GetPropValue<int>(now, "TimeOfDay.Minutes");
int hrs = now.GetPropValue<int>("TimeOfDay.Hours");
see this link for your reference.