简体   繁体   中英

How to chose between new and override in C#?

It is advised to use override instead of new key word in C#. Why that rule?

"new" means you've got two completely different methods as far as the CLR is concerned - they happen to have the same name, but they're unrelated in terms of inheritance. That means that if you run:

Base b = new Derived();
Derived d = new Derived();
b.MyMethod(); // Calls Base.MyMethod
d.MyMethod(); // Calls Derived.MyMethod

This can make for some very hard-to-understand code.

Usually if you want different methods, call them different things. The normal reason to use the same name (and signature) is to override the behaviour of a base class's method. At that point you don't have any choice but to keep the name/signature the same.

我仍然试图找出除了可怕的hackery之外的“新”用例。

This is actually not a choice you have. This is imposed upon you by however created the base class. If there exists a method with the same name and it is marked as "virtual" then you should use override unless you want to have some seriously funny bugs appearing down the road when people starts casting objects of your class to the base class...

Though if that method is NOT marked as "virtual" then the only way to create a NEW method is by using the "new" keyword. Note though that this will not replace method invocations where the reference is of typeof(baseclass) to your method. So this is mostly just syntactical sugar to create a new method with the same name and the same signature...

Though when code hits your iron it's nothing else then a completely different method with the same name and the same signature. Where an overridden method will replace every single call including those in the base class assembly to your new method...

So comparing them is like comparing cars and errh... birds or something...

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