Sealed keyword in association with override

后端 未结 4 1752
无人共我
无人共我 2021-01-07 19:53

Is it always necessary to follow the sealed keyword with override in the signature of a method like the below code:

public sealed o         


        
4条回答
  •  时光取名叫无心
    2021-01-07 20:27

    Sealing a method only makes sense if you override it.

    What happens here is the following:
    You are overriding a method from a base class (override) and tell the compiler that classes derived from your class are no longer allowed to override this method (sealed).

    If the method is a new one declared by you in your class and you want to prevent derived classes from overriding it, simply don't declare it as virtual.

    If the method is declared in a base class but is not overridable sealing it wouldn't make any sense, because it already can't be overriden.

提交回复
热议问题