【问题标题】:Nested fully qualified property name using reflection使用反射的嵌套完全限定属性名称
【发布时间】:2016-09-02 23:44:18
【问题描述】:

我有以下课程:

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; } 
}

我正在使用这个获取所有嵌套属性:

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 };
        }

这给了我类的所有属性。但是,当我尝试从对象中获取嵌套属性时,出现异常:

horsePowerProperty.GetValue(myCar); // object doesn't match target type exception

发生这种情况是因为它在 Car 对象上找不到属性 HorsePower。我查看了PropertyInfo 上的所有属性,似乎找不到任何具有完全限定属性名称的地方。然后我将使用它来拆分字符串,并递归地从 Car 对象中获取属性。

任何帮助将不胜感激。

【问题讨论】:

  • 你这样做有什么原因吗?
  • 除非有更好的方法来解决这个问题@MatiasCicero ?
  • 试图弄清楚你想要完成什么。如果您知道要查找 HorsePower,那么您可能已经知道对象的结构。
  • 我正在尝试对任何类型的对象进行一般性操作@itsme86
  • 您可以使用属性信息的ReflectedTypeDeclaringType 来确定该属性属于哪种类型...但我认为没有办法(至少使用PropertyInfo ) 你可以得到 PI 属于哪个“一流”属性。 PropertyInfos 提供关于类型的信息,而不是关于类成员的信息。

标签: c# .net reflection


【解决方案1】:

(没有测试过)

你可以使用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);
}

这要求如果HorsePower 属于Engine 类型,则您的Car 类型中需要有一个名为Engine 的属性。

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 2023-04-10
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2014-02-25
    相关资源
    最近更新 更多