虚拟方法 [英] virtual methods

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

问题描述

如果我有一个名为为例类。他有一个命名的方法打印。
小子导出,它有一个方法命名为打印,而是一个新的。

If I have a class named "Parent" for example. he has a method named "Print". the class "Kid" is derived, it has a method named "Print", but a new one.

new public void Print;

让我们创建一个对象:

Parent p = new Kid();

如果我使用的方法与此对象的指针,$ B $打印B中的方法将是父亲(父)方法,而不是孩子。

If I'll use the method Print with this object's pointer the method will be the father's("Parent") method, not the "Kid".

但是,当我使用的是虚拟的方法,该方法将孩子的不是父。(如果打印是虚拟的,在小子打印覆盖方法)

But when I'm using a virtual method, the method will be the Kid's not the parent.(if the Print was virtual, the print in the "Kid" overrides the method")

为什么?

推荐答案

当你使用new关键字与具有相同签名,在父母的方法的方法,它屏蔽了该父方法。阴影是压倒一切的不同。阴影意味着你的新方法将被调用。如果两个实例和变量的类型为孩子而压倒一切,确保您的覆盖方法将被调用,不管变量的类型为子女或父母

When you use the new keyword with a method having same signature as that of a method in parent, it shadows the parent method. Shadowing is different from overriding. Shadowing means your new method will be called if both instance and variable are of type child. Whereas overriding ensures that your overriden method will be called no matter variable is of type child or parent.

编辑:

看看在比较表的MSDN上。

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

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