[英]Can we declare sealed method in a class
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 : 在上面的代码中有编译时错误:
XF()' cannot be sealed because it is not an override XF()'不能密封,因为它不是替代
X.F1()' cannot be sealed because it is not an override X.F1()'无法密封,因为它不是替代
Does it mean we can only apply the sealed
keyword whey we have to override some methods? 这是否意味着我们只能应用必须重写某些方法的sealed
关键字whey?
Well, sealed keyword prevents method from being overriden , and that's why it doesn't make sence 好吧, 密封关键字防止方法被覆盖 ,这就是为什么它没有意义
virtual
instead of declaring virtual sealed
. 使用虚拟声明-只需删除virtual
而不是声明virtual sealed
。 So the only option is override sealed
which means override, but the last time : 因此,唯一的选择是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() {;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.