且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#中的虚拟关键字

更新时间:2022-05-31 03:37:35

您需要的,如果在虚拟关键字你真的想在子类覆盖方法。否则,基本实现将被新的执行被隐藏,就像您曾与关键字来声明它。

You need the virtual keyword if you really want to override methods in sub classes. Otherwise the base implementation will be hidden by the new implementation, just as if you had declared it with the new keyword.

通过被宣布为压倒一切他们没有基本方法隐藏方法虚拟让你不用多态,这意味着:如果你投的专用版本,以基地版本,并调用一个方法,始终是基类的实现将被使用的重写版本 - 这是不是你所期望的是什么

Hiding the methods by "overriding" them without the base method being declared virtual leaves you without polymorphism, that means: if you "cast" a specialized version to the "base" version and call a method, always the base classes implementation will be used instead of the overridden version - which is not what you'd expect.

例如:

class A
{
    public void Show() { Console.WriteLine("A"); }
}

class B : A
{
    public void Show() { Console.WriteLine("B"); }
}

A a = new A();
B b = new B();

a.Show(); // "A"
b.Show(); // "B"

A a1 = b;
a1.Show(); // "A"!!!