class X {
sealed protected virtual void F() {
Console.WriteLine("X.F");
}
sealed void F1();
protected virtual void F2() {
Console.WriteLine("X.F2");
}
}
在上面的代码中有编译时错误:
X.F()'无法密封,因为它不是覆盖
X.F1()'无法密封,因为它不是覆盖
这是否意味着我们只能应用sealed
关键字来覆盖某些方法?
答案 0 :(得分:5)
好吧,密封的关键字可以防止方法被覆盖,这就是为什么它没有出现
virtual
,而不是声明virtual sealed
。所以唯一的选择是override sealed
,这意味着覆盖,但最后一次:
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() {;}
}