我们可以在 class 中声明密封方法吗

Can we declare sealed method in a class

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

以上代码存在编译时错误:

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

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

这是否意味着我们只能应用 sealed 关键字而我们必须覆盖某些方法?

嗯,sealed 关键字防止方法被 overriden,这就是为什么它没有意义

  1. with virtual 声明 - 只需删除 virtual 而不是声明 virtual sealed.
  2. 关于抽象方法,因为必须重写抽象方法
  3. 关于非虚拟方法,因为这些方法不能被覆盖

所以唯一的选择是override sealed,这意味着覆盖,但是最后一次

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() {;}
}