使用反射嵌套的完全限定属性名
本文关键字:属性 反射 嵌套 | 更新日期: 2023-09-27 18:05:36
我有以下类:
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
对象获得属性。
(还没有测试这个)
可以使用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
的属性。