在方法签名中使用新关键字通常只是为了可读性? [英] Is using new keyword in method signature generally just for readability?

查看:139
本文介绍了在方法签名中使用新关键字通常只是为了可读性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读关键字在方法签名,并已看到下面的示例帖子,但我还是不明白为什么写 new 关键字在方法签名中。如果我们忽略它,它仍然会做同样的事情。它会编译。

I've read about new keyword in method signature and have seen the example below on this post, but I still don't get why to write new keyword in method signature. If we'll omit it, it still will do the same things. It will compile. There is gonna be a warning, but it will compile.

因此,在方法签名中写入 new 只是为了可读性?

So, writing new in method signature is just for readability?

public class A
{
   public virtual void One() { /* ... */ }
   public void Two() { /* ... */ }
}

public class B : A
{
   public override void One() { /* ... */ }
   public new void Two() { /* ... */ }
}

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B


推荐答案

为什么隐藏基类成员时不需要 new 关键字?原因是脆弱的基类问题。假设你有一个库:

Implicit in this question: why isn't the new keyword required when hiding a base class member? The reason is the brittle base class problem. Suppose you have a library:

public class Base
{
    public void M() { }
}

您已经在自己的代码库中派生了一个类:

and you've derived a class in your own code base:

public class Derived : Base
{
    public void N() { }
}

现在,库作者发布了一个新版本,向 Base

Now, the library authors release a new version, adding another method to Base:

public class Base
{
    public void M() { }
    public void N() { }
}

隐藏,你的代码现在无法编译!将新关键字设为可选意味着您现在所拥有的是一个新的警告。

If the new keyword were required for method hiding, your code now fails to compile! Making the new keyword optional means that all you now have is a new warning to worry about.

EDIT

正如Eric Lippert在他的评论中指出的,新警告担心大大低估了警告的目的,即挥动大红旗。当我写信的时候,我一定很匆忙;

As Eric Lippert points out in his comment, "new warning to worry about" drastically understates the purpose of the warning, which is to "wave a big red flag." I must have been in a hurry when I wrote that; it's annoying when people reflexively view warnings as annoyances to be tolerated rather than treating them as useful information.

EDIT 2

我终于找到了这个答案的源代码,当然,这是Eric的帖子之一: http ://stackoverflow.com/a/8231523/385844

I finally found my source for this answer, which, of course, is one of Eric's posts: http://stackoverflow.com/a/8231523/385844

这篇关于在方法签名中使用新关键字通常只是为了可读性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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