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

Bh0*_*han 2 c# oop overriding sealed

class X {
    sealed protected virtual void F() {
        Console.WriteLine("X.F");
    }
    sealed void F1();
    protected virtual void F2() {
        Console.WriteLine("X.F2");
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中有编译时错误:

XF()'不能密封,因为它不是替代

X.F1()'无法密封,因为它不是替代

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

Dmi*_*nko 5

好吧,密封关键字防止方法被覆盖,这就是为什么它没有意义

  1. 使用虚拟声明-只需删除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() {;}
}
Run Code Online (Sandbox Code Playgroud)