【发布时间】:2011-02-12 19:33:02
【问题描述】:
我正在寻找一种解决方案来访问一个类的“扁平化”(最低)属性值及其通过属性名称的反射派生的。
即从 ClassB 或 ClassC 类型访问 Property1 或 Property2 :
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
{
}
使用简单的反射一直有效,直到您拥有被覆盖的虚拟属性(即 ClassB 中的 Property1)。然后你会得到一个 AmbiguousMatchException 因为搜索者不知道你是想要主类的属性还是派生类的属性。
使用 BindingFlags.DeclaredOnly 可以避免 AmbiguousMatchException,但会省略未覆盖的虚拟属性或派生类属性(即 ClassB 中的 Property2)。
这种糟糕的解决方法是否有替代方法:
// 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);
此外,此解决方法不能解决第二级属性的反射:从 ClassC 和 AmbiguousMatchException 获取 Property1 又回来了。
我的想法:除了循环我别无选择... Erk... ??
我对 Emit、Lambda(Expression.Call 可以处理这个问题吗?)甚至 DLR 解决方案持开放态度。
谢谢!
【问题讨论】:
标签: c# .net reflection