在C#中的虚拟关键字

编程入门 行业动态 更新时间:2024-10-20 03:33:22
本文介绍了在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#中的虚拟关键字

本文发布于:2023-11-11 06:03:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关键字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!