简体   繁体   中英

Difference between new and override?

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 ?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM