Nested fully qualified property name using reflection

佐手、 提交于 2020-01-02 21:47:34

问题


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:


(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.



来源:https://stackoverflow.com/questions/39296092/nested-fully-qualified-property-name-using-reflection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!