简体   繁体   English

使用反射嵌套的完全限定属性名称

[英]Nested fully qualified property name using reflection

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. 发生这种情况是因为在Car对象上找不到属性HorsePower I have looked at all of the properties on PropertyInfo and can't seem to find anywhere that has the fully qualified property name. 我已经查看了PropertyInfo上的所有PropertyInfo ,但似乎找不到任何具有完全限定属性名称的地方。 I would then use this to split strings, and recursively get the properties from the Car object. 然后,我将使用它来拆分字符串,并从Car对象递归获取属性。

Any help would be appreciated. 任何帮助,将不胜感激。

(Haven't tested this) (尚未测试)

You can use MemberInfo.DeclaringType : 您可以使用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. 这要求如果HorsePower属于Engine类型,则您需要在Car类型中具有一个称为Engine的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM