C# 中的 override 和 new 关键字有什么区别? [英] What is the difference between the override and new keywords in C#?
问题描述
在类层次结构中定义方法时,C# 中的 override
和 new
关键字有什么区别?
What is the difference between the override
and new
keywords in C# when defining methods in class hierarchies?
推荐答案
以下页面很好地总结了您的问题.
The following page summarizes your question very nicely.
总结
覆盖:当基类的方法在派生类中被覆盖时,会使用派生类中的版本,即使调用代码不知道"该对象是派生类的一个实例.
Override: When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn't "know" that the object was an instance of the derived class.
New:如果使用new关键字而不是override,则派生类中的方法不会覆盖基类中的方法,只是将其隐藏起来.
New: If you use the new keyword instead of override, the method in the derived class doesn't override the method in the base class, it merely hides it.
如果您没有指定 new 或 overrides,则结果输出与您指定 new 的结果相同,但您还会收到编译器警告(因为您可能不知道您在其中隐藏了一个方法)基类方法,或者实际上您可能想要覆盖它,只是忘记包含关键字).
If you don't specify either new or overrides, the resulting output is the same as if you specified new, but you'll also get a compiler warning (as you may not be aware that you're hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
Override:与基类中的虚拟/抽象/覆盖类型的方法一起使用
Override: used with virtual/abstract/override type of method in base class
新:当基类没有将方法声明为虚拟/抽象/覆盖时
New: when base class has not declared method as virtual/abstract/override
这篇关于C# 中的 override 和 new 关键字有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!