密封
應用於類時,sealed
修飾符可防止其他類繼承它。
class A { }
sealed class B : A { }
class C : B { } //error : Cannot derive from the sealed class
當應用於 virtual
方法(或虛擬屬性)時,sealed
修飾符會阻止在派生類中覆蓋此方法(屬性)。
public class A
{
public sealed override string ToString() // Virtual method inherited from class Object
{
return "Do not override me!";
}
}
public class B: A
{
public override string ToString() // Compile time error
{
return "An attempt to override";
}
}