Can we declare sealed method in a class

2020-03-27 09:56发布

问题:

class X {
    sealed protected virtual void F() {
        Console.WriteLine("X.F");
    }
    sealed void F1();
    protected virtual void F2() {
        Console.WriteLine("X.F2");
    }
}

In the above code there is compile time error :

X.F()' cannot be sealed because it is not an override

X.F1()' cannot be sealed because it is not an override

Does it mean we can only apply the sealed keyword whey we have to override some methods?

回答1:

Well, sealed keyword prevents method from being overriden, and that's why it doesn't make sence

  1. with virtual declaration - just remove virtual instead of declaring virtual sealed.
  2. on abstract methods, since abstract methods must be overriden
  3. on non-virtual methods, since these methods just can't be overriden

So the only option is override sealed which means override, but the last time:

public class A {
  public virtual void SomeMethod() {;}

  public virtual void SomeOtherMethod() {;}
}

public class B: A {
  // Do not override this method any more
  public override sealed void SomeMethod() {;}

  public override void SomeOtherMethod() {;}
}

public class C: B {
  // You can't override SomeMethod, since it declared as "sealed" in the base class
  // public override void SomeMethod() {;}

  // But you can override SomeOtherMethod() if you want
  public override void SomeOtherMethod() {;}
}