使用反射嵌套的完全限定属性名称 [英] Nested fully qualified property name using 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; }
}
我正在使用以下方法获取所有嵌套的属性:
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
之所以发生这种情况,是因为它在 Car
对象上找不到属性 HorsePower
.我查看了 PropertyInfo
上的所有属性,似乎找不到任何具有完全限定属性名称的地方.然后,我将使用它来拆分字符串,并从 Car
对象中递归获取属性.
This happens because it can't find the property HorsePower
on the Car
object. I have looked at all of the properties on PropertyInfo
and can't seem to find anywhere that has the fully qualified property name. I would then use this to split strings, and recursively get the properties from the Car
object.
任何帮助将不胜感激.
推荐答案
(尚未测试)
您可以使用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
的属性.代码>类型.
This requires that if HorsePower
belongs to type Engine
, you need to have a property called Engine
in your Car
type.
这篇关于使用反射嵌套的完全限定属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!