你为什么要躲使用`new`的方法? [英] Why would you want to hide a method using `new`?

查看:96
本文介绍了你为什么要躲使用`new`的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
   C# - 在方法签名的新关键字

让我们说我有3类:爷爷,爸爸,儿子。儿子爸爸,从爷爷继承继承。

Let's say I have 3 classes: GrandDad, Dad, Son. Son inherits from Dad, which inherits from GrandDad.

每个类实现富。

// GrandDad class: 
public virtual void foo()

// Dad class: 
new public virtual void foo()

// Son class: 
public override void foo()

我不明白其中的道理,为什么父亲会使用的新的的关键字。据我了解,使用的新的的隐藏的方法。你为什么要这么做?

I don't understand the reason as to why Dad would use the new keyword. As I understand, using new hides a method. Why would you want to do this?

我看了新的MSDN的解释,但讨论只是机械式的,而不是建筑。

I read the MSDN explanation of new, but the discussion was only mechanical, rather than architectural.

感谢

推荐答案

您presented code是不是一个很好的例子,但一个总的使用案例'新'是,如果一个基类被修改添加一个新的方法(通常是一个基类超出你的控制),但你现有的code需要调用你的派生类的方法具有相同的名称。更改派生类的方法,以新可以让你保持你的公共接口的现有消费者兼容。

Your presented code isn't a very good example, but one general use case for 'new' is if a base class is modified to add a new method (typically a base class beyond your control), but you have existing code that needs to call your derived class method with the same name. Changing the derived class method to 'new' allows you to remain compatible with existing consumers of your public interface.

这篇关于你为什么要躲使用`new`的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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