简体   繁体   中英

C# - when do I need override? When don't I need it?

I am using C# with Unity3d.

When I use Monobehaviour and create an Update method, I don't need to use the override keyword.

When I create my own class and override a function, I do need to use the override keyword.

Why is that? Why do I not need the override keyword when creating the Update method?

I think your confusion comes from the fact that Unity does something special about these methods ( Update , Start , Awake , etc). You can declare them as private and even then they will be called. That's not achievable using the language unless you use reflection , but I was told they don't use it, so I don't know what they do. And honestly, it doesn't matter. Because you can think as this being an exception to the language, that is, these methods will be called if you implement them. Simply that.

For all the rest, you have to follow the language. Here is a rough explanation:

You can or have to override a method if it is marked as abstract or virtual in the base class.

A method is abstract when the base class wants its children to implement it. A method is virtual when the base class offers an implementation of it but also offers an opportunity for the children to implement/modify that method.

So why can't all methods be "overridable"? To protect the base class developer's intention. You'd be changing the behaviour of a base class, you don't know if the base class developer would like you to do this. It's like a security lock. So that's why you have the three words abstract , virtual and override , to communicate the API intentions from the base class to their children.

You need to use the override , when you derive a class from another class and you need to change the code of a method of the base class that is virtual . This way the inheritted method of the base class can have a different behaviour -more suitable- for the derived class.

More generally, as it is stated in MSDN :

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

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