C#“new”关键字

97nico

这是 Micosoft 对new关键字的定义:“警告说DerivedClass 中的 Method2 方法 隐藏BaseClass中的 Method2方法。” https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords

我似乎无法理解为什么将其定义为“隐藏基类的实现”。如果它实际上“隐藏”了基类的实现,为什么它使用基类的实现而不是派生类的实现?在我看来,“隐藏”一词的使用与其实际工作方式相矛盾,并且这种解释倾向于关键字override实际在做什么;使用派生类的实现而不是基类的实现。

我很感激任何通过使用new关键字消除我对“基类实现隐藏”的困惑的答案谢谢大家!

大卫布朗 - 微软

为什么它使用基类的实现而不是派生类的实现

使用'new',当在基类变量上调用时,它将调用基类的实现。当在派生类变量上调用时,它将调用派生类的实现。

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

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

使用“覆盖”,派生类的实现在两种情况下都会被调用。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章