[英]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.