Can't use virtual and override on the same method in C#

后端 未结 6 1497
你的背包
你的背包 2020-12-15 04:53

So apparently you cannot use the virtual modifier with the override modifier.

virtual - a method that can be overridden

<
6条回答
  •  执念已碎
    2020-12-15 05:27

    You can declare a certain method as virtual only once, but you can override it as many times as you want - an override is not final, and it does not limit classes that inherit from the first overriding class. The method that will eventually execute is the last one the overrides the virtual method. So your code does behave as expected.

    C# is very verbose with regard to overriding - you have more specifiers than C++ or Java. It is so to let the programmer specify the exact intent:

    • You use virtual to specify a method can be overridden by subclasses.
    • You use override to specify you are overriding a method that you know is virtual (if it's not, the compiler will report an error).
    • You use sealed to prevent further overriding.
    • And you use new to hide instead of override.

    This can be confusing and sometimes annoying, but it ensures you actually know what you're doing, and it makes your intention self-documented.

提交回复
热议问题