为什么 List不是密封的?

发布于 2024-10-14 06:29:28 字数 287 浏览 3 评论 0原文

在阅读 这个问题;这基本上表明 List 没有虚拟方法,因为它被设计为“快速,不可扩展”。

如果这是设计目标,为什么最初的设计不包括密封类呢? (我知道现在这是不可能的,看看这会如何破坏客户端代码中的很多子类)

This question came to mind after reading the answer to this question; which basically made the point that List<T> has no virtual methods, since it was designed to be "fast, not extensible".

If that's the design goal, why didn't the original design including sealing the class? (I know that's not possible now, seeing how that would break a lot child classes within client code)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

允世 2024-10-21 06:29:28

没有令人信服的理由将其密封。从它中派生出来并没有什么害处。我曾经持有相反的心态——只保留你想让人们从中获得的东西。但事后看来,这没有任何意义。 .NET 的立场是方法默认是非虚拟的,但类默认是未密封的。 List 只是遵循相同的做法。

当您想要密封一个类时,它确实覆盖了虚拟方法,但进一步的子类化并不容易或不明显。从 Dictionary 等集合派生来保留已知类型参数并避免在应用程序中使用时避免将其键入,这可能会稍微有用。例如,您可能有一个派生自 Dictionary 的 QueryString 类。

由于没有虚拟方法,因此实际上没有什么可以通过密封类来保护它。

There's no compelling reason to seal it. It does no harm to derive from it. I used to be of the opposite mindset - only leave things unsealed that you intend for people to derive from. But in hindsight, it makes no sense. .NET takes the position that methods are non-virtual by default but classes are unsealed by default. List<T> just follows that same practice.

Where you would want to seal a class is when it does override virtual methods but further subclassing is not easy or obvious. It can be slightly useful to derive from a collection such as Dictionary<TKey,TValue> to stick in known type parameters and avoid typing them out if used in an application. For example maybe you would have a QueryString class that derives from Dictionary<String,String>.

And since there's no virtual methods, there's really nothing to protect the class against by sealing it.

如何视而不见 2024-10-21 06:29:28

他们决定不密封 List 的原因一定有很多,但是,一种可能是 Framework 设计团队希望与 ArrayList(未密封)平起平坐。 )以便基于扩展ArrayList进行设计的现有程序和框架能够更轻松地升级其设计以使用List。使 List 密封对于这些用途来说是一个真正的死胡同,强有力的指导性设计选择之一是允许人们轻松地从 升级他们现有的代码库ArrayListList

There must be many reasons why they decided not to make List<T> sealed, however, one possibility is that the Framework design team wanted parity with ArrayList (which is not sealed) so that existing programs and Frameworks which had designs based on extending ArrayList would be able to more easily upgrade their designs to use List<T>. Making List<T> sealed would have been a real dead-end for these uses and one of the strong guiding design choices would have been to allow people to easily upgrade their existing code-bases from ArrayList to List<T>.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文