我想了解C#中继承的基础知识,并意识到我对范围和可访问性的理解存在差距。一个例子来说明:当覆盖vs隐藏基类方法时C#范围差异
using System.Windows.Forms;
namespace InheritanceTests {
class Program {
public static void Main() {
(new A()).Foo(); // A: 1
(new B()).Foo(); // B: 2
((A)(new B())).Foo(); // B: 2 (+)
(new C()).Foo(); // C: 3
((A)(new C())).Foo(); // A: 1 (++)
}
}
class A {
private int x = 1;
public virtual void Foo() { MessageBox.Show("A: " + this.x); }
}
class B : A {
private int x = 2;
public override void Foo() { MessageBox.Show("B: " + this.x); }
}
class C : A {
private int x = 3;
public new void Foo() { MessageBox.Show("C: " + this.x); }
}
}
我有问题(+)和(++),很可能涉及:
关于(+),为什么是B
实例的私有字段x
访问即使投到A
?
关于(++),为什么当A
的Foo
方法执行时this.x
没有评估为3?