【发布时间】:2010-09-22 03:11:19
【问题描述】:
考虑一下这组有趣的类型:
class A { public virtual int MyProperty { get; set; } }
class B : A { public override int MyProperty { get; set; } }
class C : B { public new virtual int MyProperty { get; set; } }
class D : C { public override int MyProperty { get; set; } }
class E : D { public new int MyProperty { get; set; } }
我在这里看到三个不同的属性,其中五个实现相互隐藏或覆盖。
我正在尝试获取类型 E 的属性集声明:
A.MyProperty
C.MyProperty
E.MyProperty
但我下面的代码给了我一组属性实现:
A.MyProperty
B.MyProperty
C.MyProperty
D.MyProperty
E.MyProperty
我需要做什么才能获得属性声明?
或者对于E 的任何实例,B.MyProperty 是否有可能返回 A.MyProperty 以外的值?
如果我的方法朝着错误的方向前进:如何获取一个类型的所有属性成员,包括任何隐藏的成员,但不包括那些永远不会有不同值的成员?
void GetProperties(Type type)
{
if (type.BaseType != null)
{
GetProperties(type.BaseType);
}
foreach (var item in type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("{0}.{1}", type.Name, item.Name);
}
}
期望的输出:
typeof(A) typeof(B) typeof(C) typeof(D) typeof(E) ------------ ------------ ------------ ------------ -- ---------- A.MyProperty A.MyProperty A.MyProperty A.MyProperty A.MyProperty C.我的属性 C.我的属性 C.我的属性 E.MyProperty【问题讨论】:
-
我相信这是我第一次看到
new virtual.花了我一秒钟来理解它的意图。 -
我花了一些时间研究反射对象,才弄清楚如何做到这一点。我认为一旦你弄清楚如何根据这些反射对象来表达这个问题,这个问题就会变得容易得多。弄清楚后,我将问题改写为“列出指定类层次结构中的所有基本属性声明”。
标签: c# .net reflection