Sealed keyword in association with override

后端 未结 4 1730
无人共我
无人共我 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:16

    I think Mr. Hilgarth has provided the best answer here , but just to add something new for programmers who have a previous background in Java(like myself), I think most programmers new to C#, tend to confuse sealed with final in Java with respect to overriding.

    In Java, the default behaviour without specifying "any" modifier is that the method can be overriden in its derived classes.

    While in C#, the default behaviour is that the method cannot be overriden unless explicitly specified using the virtual keyword.

    Hope this helps to supplement the best answer above.

    0 讨论(0)
  • 2021-01-07 20:20

    You can only seal an override, so I guess the answer is yes.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 20:34

    Well, it technically is possible .... however, the solution is in my option kinda dirty.

    Imagine having a class A (either in your code base or an external library):

    public class A
    {
        public virtual void M () { /* implementation */ }
    }
    

    You could define an (abstract) class B : A as follows:

    public class B : A
    {
        public sealed override void M() => base.M();
    }
    

    Any class C : B would not be able to override A.M as you have sealed the method (even though you made no semantic changes).

    0 讨论(0)
提交回复
热议问题