这是代码:如何从基类访问私有阴影常量?
void Main()
{
Base.Title.Dump("Base"); // displays "Base Title"
Child.Title.Dump("Child"); // displays "Base Title"
Base baseClass = new Base();
Base childClass = new Child(); // "InvalidOperationException" would be thrown
}
class Base {
public const string Title = "Base Title";
public string ClassTitle { get; set; }
public Base() {
Type type = this.GetType();
type.GetFields()
.First(item => item.Name == "Title")
.GetValue(this).Dump();
}
}
class Child : Base {
private new const string Title = "Child Title";
}
的 “InvalidOperationException异常” 异常在基本构造函数抛出。
如果派生类型试图去做的第一件事是摆脱它,也许会重新考虑这个事物是一个常量。 – 2012-01-05 16:04:56
基类应该不知道它的子类。如果你是编码,否则你违反开放 - 闭合原则。 – 2012-01-05 16:10:10
我正在对旧代码进行维护,我试图不触及数百个子类。 – acermate433s 2012-01-05 16:19:46