我已经阅读了方法签名中的新关键字,并在
this帖子中看到了下面的示例,但我仍然不明白为什么要在方法签名中编写新关键字.如果我们省略它,它仍然会做同样的事情.它会编译.会有一个警告,但它会编译.
- 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
解决方法
隐含在这个问题中:隐藏基类成员时为什么不需要新的关键字?原因是脆弱的基类问题.假设你有一个库:
- public class Base
- {
- public void M() { }
- }
并且您已经在自己的代码库中派生了一个类:
- public class Derived : Base
- {
- public void N() { }
- }
- public class Base
- {
- public void M() { }
- public void N() { }
- }
如果方法隐藏需要new关键字,那么您的代码现在无法编译!使新关键字可选意味着您现在拥有的所有内容都是一个值得担心的新警告.
编辑
正如Eric Lippert在评论中指出的那样,“担心的新警告”大大低估了警告的目的,即“挥动大红旗”.我写这篇文章的时候一定很匆忙;当人们反复地将警告视为可以容忍的烦恼而不是将其视为有用信息时,这是令人讨厌的.
编辑2
我终于找到了这个答案的来源,当然,这是Eric的帖子之一:https://stackoverflow.com/a/8231523/385844