C# "new" 关键字

C# "new" keyword

这是 Micosoft 对 new 关键字的定义:"The warning says that the Method2 method in DerivedClass hides the Method2 method in BaseClass." (https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords)

我似乎无法理解为什么它被定义为 "hiding the implementation of the base class"。为什么它使用基础 class' 实现而不是派生 class' 实现,如果它实际上 "hides" 基础 class' 实现?在我看来,单词 "hide" 的使用与其实际工作方式相矛盾,并且该解释倾向于关键字 override 实际在做什么;使用派生的 class' 实现而不是基础 class' 实现。

如果能通过使用 new 关键字来消除我对此 "base class implementation hiding" 的困惑,我将不胜感激。谢谢大家!

我会这样想:

Derived隐藏基classBase的一个成员时,你通过Derived访问,Deriveds被调用,因为它隐藏了Base 的实施。但是,当通过 Base 时,没有任何东西隐藏它,因此使用 Bases 实现。

然而,使用virtual/override(多态性)Bases 方法实际上被覆盖,而不是隐藏,所以它会使用Deriveds 方法,即使通过Base参考。

另外(可能是真正的原因):给东西命名很难。程序员和其他人一样糟糕。

Why does it use base class' implementation instead of derived class' implementation

使用 'new',当调用基础 class 变量时,它将调用基础 class 的实现。 当调用派生的 class 变量时,它将调用派生的 class 的实现。

Derived d = new Derived();
Base b = d;

d.Foo(); //<- Derived's implementation
b.Foo(); //<- Base's implementation

对于 'override',派生的 class 的实现在两种情况下都会被调用。

Derived d = new Derived();
Base b = d;

d.Foo(); //<- Derived's implementation
b.Foo(); //<- Derived's implementation