在C#中的虚拟关键字 [英] virtual keyword in c#

查看:116
本文介绍了在C#中的虚拟关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Java知识,并一直在学习C#的最后几天。现在,我所遇到的虚拟的关键字,正如在的此链接,是用来让对应的方法,属性等在子类中重写。现在,我想我们可以覆盖方法,即使不使用虚拟的关键字。那么,为什么有必要吗?

I have knowledge of java and have been learning c# for the last couple of days. Now I have come across the "virtual" keyword which, as suggested at this link, is used to allow the corresponding methods, properties etc. to be overriden in the subclasses. Now I think we can override methods even without using the "virtual" keyword. Then why it is necessary?

推荐答案

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

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"!!!

这篇关于在C#中的虚拟关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆