0
这是有关阴影和重写在MSDN一个例子:因为A A = B影子vs覆盖?
using System;
namespace test
{
class A
{
public void F() { Console.WriteLine("A.F"); }
public virtual void G() { Console.WriteLine("A.G"); }
}
class B : A
{
new public void F() { Console.WriteLine("B.F"); }
public override void G() { Console.WriteLine("B.G"); }
}
class Test
{
static void Main()
{
B b = new B();
A a = b;
a.F();
b.F();
a.G();
b.G();
Console.WriteLine();
}
}
}
A.F();
B.F();
B.G();
B.G();
I was expecting the out put will be
B.F(); //change is here
B.F();
B.G();
B.G();
; a拥有b对象引用,因此它具有调用派生类函数。
为什么A的函数被调用?
A a = b;这意味着变量a只有类A的数据而不是b – Raghavendra
是的,但是当b指向类型B的对象时,a的指针是A类型的,所以在编译时,在a上调用的方法将会是隐含地实现A.它将保存类A的数据,但它仍然是类型B(它也是类型A)。 –