为什么要使用“new"隐藏方法? [英] Why would you want to hide a method using `new`?

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

问题描述

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

假设我有 3 个班级:爷爷、爸爸、儿子.儿子继承爸爸,爸爸继承爷爷.

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

每个类都实现了 foo.

Each class implements foo.

// GrandDad class: 
public virtual void foo()

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

// Son class: 
public override void foo()

我不明白为什么爸爸会使用 new 关键字.据我了解,使用 new 隐藏了一个方法.为什么要这样做?

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 对 new 的解释,但讨论只是机械的,而不是架构的.

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

谢谢

推荐答案

您提供的代码不是一个很好的示例,但是new"的一个一般用例是修改基类以添加新方法(通常是您无法控制的基类),但您有需要调用具有相同名称的派生类方法的现有代码.将派生类方法更改为new"可让您与公共接口的现有使用者保持兼容.

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天全站免登陆