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

我有以下课程:

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 GetProperties(PropertyInfo propertyInfo) { if (propertyInfo.PropertyType.IsClass) { return propertyInfo.PropertyType.GetProperties().SelectMany(prop => GetProperties(prop)).ToList(); } return new [] { propertyInfo }; } 

这给了我class级的所有属性。 但是,当我尝试从对象获取嵌套属性时,我得到一个exception:

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

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

任何帮助,将不胜感激。

(还没试过这个)

您可以使用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的属性。