I have the following classes:
public class Car
{
public Engine Engine { get; set; }
public int Year { get; set; }
}
public class Engine
{
public int HorsePower { get; set; }
public int Torque { get; set; }
}
I'm getting all the nested properties using this:
var result = typeof(Car).GetProperties(BindingFlags.Public | BindingFlags.Instance).SelectMany(GetProperties).ToList();
private static IEnumerable<PropertyInfo> GetProperties(PropertyInfo propertyInfo)
{
if (propertyInfo.PropertyType.IsClass)
{
return propertyInfo.PropertyType.GetProperties().SelectMany(prop => GetProperties(prop)).ToList();
}
return new [] { propertyInfo };
}
This gives me all the properties of the class. However, when I try and get a nested property from an object, I get an exception:
horsePowerProperty.GetValue(myCar); // object doesn't match target type exception
This happens because it can't find the property HorsePower
on the Car
object. I have looked at all of the properties on PropertyInfo
and can't seem to find anywhere that has the fully qualified property name. I would then use this to split strings, and recursively get the properties from the Car
object.
Any help would be appreciated.
Aucun commentaire:
Enregistrer un commentaire