【发布时间】:2015-11-21 05:18:01
【问题描述】:
我希望能够在运行时使用反射动态获取覆盖属性的值。例如,
class A {
public virtual int Foo => 5;
//This implementation doesn't work
public int ParentFoo => (int)this.GetType().BaseType.GetProperty(nameof(Foo)).GetValue(this);
}
class B : A {
public override int Foo => 7;
}
var test = new B();
Console.WriteLine(test.Foo); //"7"
Console.WriteLine(test.ParentFoo); //Should display "5"
这样做的重点是类型层次结构相当深,我不希望扩展程序每次都必须使用完全相同的逻辑 (public int ParentFoo => base.Foo;) 重新实现 ParentFoo。我不介意为反射支付性能成本——这个属性不需要是高性能的。
是否可以使用反射来完成我这里需要的事情?
【问题讨论】:
标签: c# .net reflection