Nested fully qualified property name using reflect

2019-05-30 10:41发布

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.

1条回答
2楼-- · 2019-05-30 10:55

(Haven't tested this)

You can use MemberInfo.DeclaringType:

private static object GetPropertyValue(PropertyInfo property, object instance)
{
    Type root = instance.GetType();
    if (property.DeclaringType == root)
        return property.GetValue(instance);
    object subInstance = root.GetProperty(property.DeclaringType.Name).GetValue(instance);
    return GetPropertyValue(property, subInstance);
}

This requires that if HorsePower belongs to type Engine, you need to have a property called Engine in your Car type.

查看更多
登录 后发表回答