c# - 为什么在当前类是子类时对方法或属性使用 sealed

标签 c#

当当前类曾经从父类(super class)继承时,为什么我们要在方法或属性上使用 sealed 关键字?假设我们创建了一个类,并且倾向于将它的一个或多个方法暴露给对象用户,但根本不让它被继承,并使用sealed 来解决这个问题。那么,为什么不呢?仅密封当前继承类的方法或属性背后的原因是什么?

最佳答案

如 MSDN 文档中所述 sealed :

You can also use the sealed modifier on a method or property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent them from overriding specific virtual methods or properties.

换句话说,您可以阻止覆盖发生在类继承层次结构的更下方。作为一名程序员,您基本上是在说这个特定方法应该与所有子类具有共同的功能。

这是同一篇文章中的一个很好的代码示例:

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"); }
}

根据请求更新以获取更多说明

下面是一个不太抽象的例子,说明了一个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
{
}

关于c# - 为什么在当前类是子类时对方法或属性使用 sealed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034919/

相关文章:

c# - 使用扩展方法分配属性的好方法

c# - 使用 INotifyPropertyChanged 更新 WPF UI

c# - WPF 中的预测键入功能

c# - 适用于 Mac 和 Windows 的音频框架

c# - 如何推迟关闭 Windows 服务

c# - 如何使用 LINQ 或 XPath 从 XML 中获取打印的值

c# - 将2个数据表转换为一个表

C#远程web请求证书报错

c# - 如何在代码中的 TextBlock 中添加超链接?

c# - 如何让定时器只触发一次