C#virtual关键字 [英] C# virtual keyword

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

问题描述

是一个虚拟的方法,强制其子类覆盖?

Is a virtual method compulsory to override by its subclass?

推荐答案

如果方法不是虚拟的(或抽象)它不能在子类中指定。唯一的选择就是使用关键字隐藏继承的方法,但是这通常不是一个推荐的做法,因为铸造子类的实例父类和调用该方法将导致代替称为父类的方法,那就是可能不是预期功能。

If a method is not virtual (or abstract), it can't be overriden in the sub class. The only option then is to use the new keyword to hide the inherited method, but this is generally not a recommended practice, since casting the instance of the sub class to the parent class and calling the method will cause the parent class method to be called instead, and that is probably not the intended functionality.

因此,在短,是它需要虚拟到重写,但没有你不要的有无的覆盖它。如果不这样做,基类的版本将被改为调用。但是,如果你忽略它,即使你投的对象是基类,方法的派生版本将被调用,不像隐藏themethod新的。

So in short, yes it needs to be virtual to override, but no you dont have to override it. If you don't, the base class version will be called instead. But if you do override it, even if you cast the object to it base class type, the derived version of the method will be called, unlike for hiding themethod with new.

这是很好的了解覆盖和隐藏方法,因为乍一看之间的区别,如果你测试它,它可能看起来像它做同样的事情,但以后回来咬你当程序不工作正如所料,你不知道为什么。

It's good to know the difference between overriding and hiding the method, since at first glance, and if you test it, it might look like it does the same thing, but will come back to bite you later when the program don't work as expected, and you have no idea why.

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

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