Difference between new and override?

风流意气都作罢 提交于 2020-01-11 05:08:46

问题


I have a base class which I want to provide some 'base' functionality for methods for all inheriting classes.

In my inheriting classes I want to do:

public override void Setup()
{
   base.Setup();
}

But at the moment it says I have to use the new keyword.

How to I have it so I have to use the override keyword?

Is there any difference between how it is currently with me using the new keyword and using override?


回答1:


It says so because you have not declared the base method virtual. Once you do so, the base virtual/derived override pair of keywords will make sense. Right now, the compiler is complaining that you cannot override a non-virtual method.




回答2:


When you use the override keyword the derived method is used even when the instance is passed as a Base class type. Hence there needs to be a virtual in the base class so that the programme knows it has to make a runtime check of what the actual type of the instance is. It then looks up what the actual type is and if it is a derived type it checks if their is an override in the derived class for that particular method in the base class.

Member hiding is different. The base member will only be hidden if it is actually passed as an instance of the derived class. If the object is passed as a base class, the base class method will still be used. If you hide a member, you get a warning if you haven't use the new keyword. The new keyword is merely to tell the complier, that you really do mean to hide the base type method.



来源:https://stackoverflow.com/questions/7542238/difference-between-new-and-override

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!