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

标签 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");
    }
}

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

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

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

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

最佳答案

嗯,sealed 关键字可以防止方法被覆盖,这就是它没有意义的原因

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

所以唯一的选择是override sealed,这意味着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() {;}
}

关于c# - 我们可以在类中声明密封方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35475278/

相关文章:

c# - 当值为 null 时,将可空 bool 值传递给部分 View 不起作用

PHP $stmt->num_rows 不适用于准备好的语句

c++ - 纯虚方法的模板特化

java - 无法覆盖 toString 方法

c# - 为什么我的子类需要用默认参数覆盖?

亚马逊产品广告 API 的 C# 库

c# - 信息重新 : add/remove methods in stringLists

c# - 具有上下文处理的异步方法

Javascript TypeError : this. init is not a function 错误

javascript - 如何按共同特征组织数据?