为什么标记为在基类中隐藏实现的方法称为隐藏方法? [英] Why can a method marked that is hiding an implementation in the base class call the hidden method?
问题描述
我一直在阅读有关C#规范的内容,并遇到了一个我没有想到的场景,并希望有人可以分享一些经验.
I've been doing a little reading around the c# spec, and come across a scenario I didn't expect, and was hoping somebody could share some light.
我偶然发现了 new
关键字,用于将基类的成员隐藏在派生类中,随后对何时使用 new
而不是< virtual
成员上的code> override .
I stumbled across the new
keyword for hiding members of a base class within a derived class, and subsequently a few discussions over when to use new
as opposed to an override
on a virtual
member.
我在IDE中放入了一些代码示例,希望看到编译错误
I threw a little code sample in to my IDE, expecting to see a compilation error
public class BaseType
{
public void method()
{
// do nothing
}
}
public class DerivedType : BaseType
{
public new void method()
{
base.method();
}
}
,但是发现这是合法的C#.由于派生类隐藏了 method()
的存在,为什么仍允许我调用它?
but instead found this to be legal c#. Since the derived class has hidden the presence of method()
, why am I still allowed to call it?
欢呼
推荐答案
DerivedType
正在从将继承 DerivedType
的类中隐藏方法,而不是从其自身隐藏.
注意,要隐藏该方法,该类必须知道其父类中存在一个具有相同名称和参数的方法.因此,一类将方法隐藏在自己的作用域内是不合逻辑的.
The DerivedType
is hiding the method from the classes which will be inheriting DerivedType
, and not from itself.
Note that, to hide the method, the class has to know there exists a method in it's parent class with the same name and same arguments. Hence one class hiding the method from it's own scope is illogical.
这篇关于为什么标记为在基类中隐藏实现的方法称为隐藏方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!