Can we declare sealed method in a class

限于喜欢 提交于 2019-12-19 10:19:58

问题


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


来源:https://stackoverflow.com/questions/35475278/can-we-declare-sealed-method-in-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!