Bh0*_*han 2 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");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中有编译时错误:
XF()'不能密封,因为它不是替代
X.F1()'无法密封,因为它不是替代
这是否意味着我们只能使用sealed必须覆盖某些方法的关键字whey?
好吧,密封关键字防止方法被覆盖,这就是为什么它没有意义
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() {;}
}
Run Code Online (Sandbox Code Playgroud)