首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么HashSet<T>不实现ICollection?

为什么HashSet<T>不实现ICollection?
EN

Stack Overflow用户
提问于 2015-07-07 15:29:58
回答 1查看 2.7K关注 0票数 8

我将编写一个库来遍历对象图(类似于某种序列化)。

您需要判断一个对象是否是遍历中的集合,因此ICollection从我的脑海中浮现出来。(string也实现了IEnumerable)

但是,非常奇怪的是,集合中的几乎所有容器都实现了ICollection,除了HashSet只实现了ICollection<T>.

我已经检出了System.Collections命名空间中几乎所有常见的容器:

代码语言:javascript
复制
ArrayList : IList, ICollection, IEnumerable, ICloneable  
BitArray : ICollection, IEnumerable, ICloneable  
Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable  
Queue : ICollection, IEnumerable, ICloneable  
SortedList : IDictionary, ICollection, IEnumerable, ICloneable  
Stack : ICollection, IEnumerable, ICloneable  
Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback
HashSet<T> : ISerializable, IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable  
LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback  
List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable  
Queue<T> : IEnumerable<T>, ICollection, IEnumerable  
SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable  
SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable  
SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback  
Stack<T> : IEnumerable<T>, ICollection, IEnumerable  

这是个虫子吗?或者背后有什么原因?

EN

回答 1

Stack Overflow用户

发布于 2019-03-07 15:45:19

当没有提供更好的类型安全性的ICollection时,.NET不再像.NET 1.1那样有用。对于ICollection,人们几乎没有什么能有效地处理ICollection<T>的,这通常具有更高的效率和/或类型安全性,特别是当您编写泛型方法时,您可能希望使用不同元素类型的集合来完成一些事情。

然而,这回避了为什么像List<T>这样的人确实实现了ICollection的问题。但是,当List<T>在.NET 2.0中引入时,所有遗留代码都使用ICollectionArrayList,而不是ICollection<T>List<T>。将代码升级到使用List<T>而不是ArrayList可能会很痛苦,特别是如果这意味着必须立即更改它将使用的ICollection的所有用法以使用ICollection<T>,或者更糟糕的是,由于一个方法正在与其他非泛型集合一起命中的List<T>被击中,所以每个方法都需要版本。实现ICollection简化了升级过程,允许人们在如何利用通用集合方面更加零敲碎打。

HashSet<T>问世时,泛型已经使用了三年,而且之前没有框架提供的非泛型哈希集类型,因此没有那么多升级痛苦,因此支持ICollection的动机也就少了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31273003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档