为什么HashSet 没有实现ICollection?

问题描述 投票:5回答:1

我将编写一个库来遍历一个对象图(就像某种序列化一样)。 你将需要判断一个对象是否是遍历中的集合,所以ICollection出现在我脑海中。 (string也实施了IEnumerable

但是真的很奇怪收藏中的几乎所有容器都实现了ICollection,除了HashSet只实现了ICollection<T> ......

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

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  

这是一个错误吗?或者背后有一些原因?

.net collections interface hashset
1个回答
0
投票

ICollection现在不像.NET 1.1那样有用,因为没有ICollection<T>提供更大的类型安全性。很少有人可以使用ICollection,而ICollection<T>无法做到这一点,通常具有更高的效率和/或类型安全性,特别是如果为那些可能想要对不同元素类型的集合做某事的情况编写泛型方法。

这虽然引起了为什么像List<T>这样的人确实实施ICollection的问题。但是当使用.NET 2.0引入List<T>时,所有遗留代码都使用ICollectionArrayList,而不是ICollection<T>List<T>。升级代码使用List<T>而不是ArrayList可能是一种痛苦,特别是如果它意味着必须立即改变使用ICollectionICollection<T>的所有用途,或者更糟糕的是,加倍因为一个方法被List<T>击中也被其他非泛型集合所击中,因此每个都需要该方法的版本。实施ICollection缓解了升级路径,允许人们更加零碎地利用通用集合。

HashSet<T>出来时,仿制药已经使用了三年,并且该框架没有提供以前的非通用哈希集类型,因此升级的痛苦较少,因此支持ICollection的动机较少。

© www.soinside.com 2019 - 2024. All rights reserved.