.net - 为什么.Net中存在 'sealed'关键字?

标签 .net keyword sealed

.Net 框架中的大量类被标记为“密封”,阻止您用自己的类继承这些类。当然,这违背了面向对象的本质,在面向对象中您可以扩展和重新定义现有对象的行为。

“sealed”关键字的存在有充分的理由吗?

As an example, NotifyCollectionChangedEventArgs in Silverlight is sealed. I wanted to create my own version of ObservableCollection that supported AddRange and RemoveRange, but the Silverlight version of NCCEA doesn't provide a constructor that supports multiple items for the NewItems and OldItems properties, which are already defined as ILists. Usually, I'd just extend the class with my own variant that overrode the NewItems and OldItems properties, but in this case I can't and I can see no reason why that should be the case.

最佳答案

将类(或框架)设计为可扩展并非易事,简单地说,继承并不是面向对象编程的唯一原则。

因此,sealed 的存在是为了允许开发人员/设计人员表达和保留这些意图。密封一个类还可以通过减少维护负担来使他们的生活更轻松。它允许原始开发人员控制类(或框架)的扩展方式,因此他们可以进行内部更改,而不必担心对其他代码的破坏性更改。

一个原则是开发人员应该默认密封任何类。然后,当开发人员有意创建未密封的类时,就会迫使他们考虑可扩展性。

<小时/>

引用:Eric Lippert - Why Are So Many Of The Framework Classes Sealed?

关于.net - 为什么.Net中存在 'sealed'关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/554894/

相关文章:

keyword - "auto," "ansi,"和 "cil managed"在 CIL 中做什么?

c# - 访问级别和修饰符(私有(private)、密封等)是否在 C# 中用于安全目的?

.net - 通过 HTTP 记录错误 - 安全隐患

c# - 将集合 (HashSet) 隐式转换为 IEnumerable<T>

c# - 无法使用 Fakes 程序集构建项目

.net - Visual Studio 2010 远程调试 - 无法连接 : Access Denied

c++ - new 的 c++ 关键字的奇怪用法

java - 在线程中使用同步

c# - 如何解决密封类的不可能继承?

c# - 为什么这个 C# 类声明可以编译?