本文介绍了我们可以在类中声明密封方法吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.F1()'不能密封,因为它不是替代

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

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

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

推荐答案

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

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

  1. 带有 virtual 声明-只需删除virtual而不是声明virtual sealed.
  2. 关于抽象方法,因为必须重写抽象方法
  3. 使用非虚拟方法,因为这些方法无法被覆盖
  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

因此唯一的选项是override sealed,这意味着覆盖,但最后一次:

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

这篇关于我们可以在类中声明密封方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 20:18