sealed当当前类从超类继承时,为什么我们要在方法或属性上使用关键字?假设我们创建了一个类,并且倾向于将其一个或多个方法公开给对象用户,但根本不让它被继承并用于sealed解决问题。那么,为什么不呢?仅密封当前继承类的方法或属性的原因是什么?
正如 MSDN 文档中关于seal 的所述:
您还可以在重写基类中的虚拟方法或属性的方法或属性上使用 seal 修饰符。这使您能够允许从您的类派生类并防止它们覆盖特定的虚拟方法或属性。
换句话说,您可以阻止在类继承层次结构中进一步发生重写。作为一名程序员,您基本上是在说这个特定方法应该与所有子类具有共同的功能。
这是同一篇文章中的一个很棒的代码示例:
class X
{
protected virtual void F() { Console.WriteLine("X.F"); }
protected virtual void F2() { Console.WriteLine("X.F2"); }
}
class Y : X
{
sealed protected override void F() { Console.WriteLine("Y.F"); }
protected override void F2() { Console.WriteLine("Y.F2"); }
}
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"); }
}
Run Code Online (Sandbox Code Playgroud)
根据额外澄清请求进行更新
下面是一个不太抽象的方法可能应用的示例sealed。
abstract class Car
{
public abstract void Make();
}
class Ford : Car
{
// We don't want someone inheriting from this class to change the
// 'Make' functionality - so we seal the method from being further
// overridden down the inheritance hierarchy
sealed public override void Make() { Console.WriteLine("Ford"); }
}
// This way there is no way (besides shadowing) someone inheriting from Ford
// can change the behavior of Make() - so these two types will contain the
// same behavior. Pretty nice, eh!?
class Focus : Ford
{
}
class Escape : Ford
{
}
Run Code Online (Sandbox Code Playgroud)