【发布时间】: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
-
您可以使用属性信息的
ReflectedType或DeclaringType来确定该属性属于哪种类型...但我认为没有办法(至少使用PropertyInfo) 你可以得到 PI 属于哪个“一流”属性。PropertyInfos 提供关于类型的信息,而不是关于类成员的信息。
标签: c# .net reflection