Can we declare sealed method in a class

前端 未结 1 414
陌清茗
陌清茗 2021-01-14 11:09
class X {
    sealed protected virtual void F() {
        Console.WriteLine(\"X.F\");
    }
    sealed void F1();
    protected virtual void F2() {
        Console.W         


        
相关标签:
1条回答
  • 2021-01-14 11:40

    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() {;}
    }
    
    0 讨论(0)
提交回复
热议问题