我正在寻找一个解决方案来访问类的“Flatten”(最低)属性值及其通过属性名反射派生的值。
IE访问
财产1
或
财产2
来自
乙类
或
小精灵
类型:
public class ClassA
{
public virtual object Property1 { get; set; }
public object Property2 { get; set; }
}
public class ClassB : ClassA
{
public override object Property1 { get; set; }
}
public class ClassC : ClassB
{
}
使用简单的反射可以工作,直到您的虚拟属性被重写(即
财产1
从
乙类
)然后你得到一个
含糊不清的匹配异常
因为搜索者不知道您想要的是主类的属性还是派生的属性。
使用bindingFlags.declaredOnly避免出现含糊不清的MatchException,但未覆盖的虚拟属性或派生类属性被忽略(即
财产2
从
乙类
)
除了这种糟糕的解决方案,还有别的办法吗?
// Get the main class property with the specified propertyName
PropertyInfo propertyInfo = _type.GetProperty(propertyName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
// If not found, get the property wherever it is
if (propertyInfo == null)
propertyInfo = _type.GetProperty(propertyName);
此外,此解决方案无法解决第二级属性的反射:获取
财产1
从
小精灵
和
含糊不清的匹配异常
回来了。
我的想法:除了循环我别无选择…尔克…???
我可以发出lambda(表达式是.call可以处理它吗?)即使是DLR解决方案。
谢谢!