Why should virtual methods be explicitly overridden in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Because it makes code more readable:
In C++, Foo may or may not be a virtual method, we can't tell by looking at the definition. In C# we know a method is virtual (or isn't) because there is either a virtual or override keyword.
Jason's comment below is a better answer.
(edited for clarity)
Not all virtual methods should be overridden, though all abstract methods should (and must) be. As for why the 'override' keyword is explicit, that's because overriding and hiding behave differently. A hiding method is not called through a reference to a base class, whereas an overridden method is. This is why the compiler specifically warns about how you should use the 'new' keyword in the case where you are hiding rather than overriding.
By declaring a method as
virtual
, you are stating your intention that the method can be overridden in a derived class.By declaring your implementing method as
override
, your are stating your intention that you are overriding avirtual
method.By requiring that the
override
keyword be used to override a virtual method, the designers of the language encourage clarity, by requiring you to state your intentions.It is because the C# team members are all skilled C++ programmers. And know how incipient this particular bug is:
It is a lot more common then you might think. The derived class is always declared in another source code file. You don't typically get this wrong right away, it happens when you refactor. No peep from the compiler, the code runs pretty normal, just doesn't do what you expect it to do. You can look at it for an hour or a day and not see the bug.
This can never happen in a C# program. Even managed C++ adopted this syntax, breaking with native C++ syntax intentionally. Always a courageous choice. IntelliSense takes the sting out the extra verbiage.
There's a lot of syntax tweaks in C# that resemble this kind of bug avoidance syntax.
EDIT: and the rest of the C++ community agreed and adopted the override keyword into the new C++11 language specification.
If you don't add the
override
keyword, the method will be hidden (as if it had thenew
keyword), not overridden.For example:
This code prints
Base
. If you addoverride
to theDerived
implementation, the code will printDerived
.You cannot do this in C++ with a virtual method. (There is no way to hide a C++ virtual method without overriding it)