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 关键字可以防止方法被覆盖,这就是它没有意义的原因
- 使用 virtual 声明 - 只需删除
virtual
而不是声明virtual sealed
。 - 在抽象方法上,因为必须覆盖抽象方法
- 在非虚拟方法上,因为这些方法不能被覆盖
所以唯一的选择是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/