为什么 List不是密封的?
在阅读 这个问题;这基本上表明 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有令人信服的理由将其密封。从它中派生出来并没有什么害处。我曾经持有相反的心态——只保留你想让人们从中获得的东西。但事后看来,这没有任何意义。 .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 fromDictionary<String,String>
.And since there's no virtual methods, there's really nothing to protect the class against by sealing it.
他们决定不密封
List
的原因一定有很多,但是,一种可能是 Framework 设计团队希望与ArrayList
(未密封)平起平坐。 )以便基于扩展ArrayList
进行设计的现有程序和框架能够更轻松地升级其设计以使用List
。使List
密封对于这些用途来说是一个真正的死胡同,强有力的指导性设计选择之一是允许人们轻松地从升级他们现有的代码库ArrayList
到List
。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 withArrayList
(which is not sealed) so that existing programs and Frameworks which had designs based on extendingArrayList
would be able to more easily upgrade their designs to useList<T>
. MakingList<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 fromArrayList
toList<T>
.