[英]Sealed must be used with override?
sealed
可防止方法被子类覆盖。 如果标记为密封的方法首先不能覆盖,为什么要将其标记为密封?
因为没有理由将它添加到不覆盖另一个类的属性的属性。 它将sealed修饰符放在派生类的属性上,它表示从您派生的任何人都无法进一步覆盖该属性。 如果该属性从一开始就不会被覆盖,那么使用密封是没有意义的。
基本上,它表示子类必须按照您的预期方式使用该属性。
因为结构是隐式密封的,所以它们不能被继承,“ 密封 ”会阻止方法被子类覆盖。
请参阅示例: In the following example, Z inherits from Y but Z cannot override the virtual function F that is declared in X and sealed in Y.
class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}
类Y继承自类X,并将函数F()定义为:sealed protected override void F()。
class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); }
protected override void F2() { Console.WriteLine("Y.F2"); }
}
从Y继承的类Z,其中函数F()被定义为密封,你可以覆盖函数,因为它定义为“密封”
class Z : Y
{
// Attempting to override F causes compiler error CS0239.
// protected override void F() { Console.WriteLine("C.F"); }
// Overriding F2 is allowed.
protected override void F2() { Console.WriteLine("Z.F2"); }
}
更多信息: 密封(C#参考)
说你有:
public BaseClass
{
public virtual void SomeMethod()
{
}
}
和:
public MyDerivedClass : BaseClass
{
public void AnotherMethod()
{
// there's no point sealing this guy - it's not virtual
}
public override sealed void SomeMethod()
{
// If I don't seal this guy, then another class derived from me can override again
}
}
然后:
public class GrandChildClass : MyDerivedClass
{
public override void AnotherMethod()
{
// ERROR - AnotherMethod isn't virtual
}
public override void SomeMethod()
{
// ERROR - we sealed SomeMethod in MyDerivedClass
// If we hadn't - this would be perfectly fine
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.