阴影与覆盖?
这是 msdn 中与遮蔽和覆盖相关的示例之一:
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 a = b; a 持有 b 对象引用,因此它有一个调用派生类函数。
为什么调用A的函数?
This is one of the examples in the msdn related to shadowing and overriding:
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();
since A a = b;
a holds the b object reference and hence it has a call derived class function.
Why is the function of A called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在运行时,虽然 a 确实是 B 类型的变量,但它显式地是 A 类型的变量 (A a = b;),因此在运行时,由于 a 被声明为 A 类型,因此 F( ) 调用 A 的方法。
希望这有帮助!
NS
At run-time, while a is indeed a variable of the type B, it's explicitly a variable of type A (A a = b;), and so at run-time since a is declared as being a type A, the F() method of A is called.
Hope this helped!
N.S.