gpt4 book ai didi

.net - 为什么HashSet 不实现ICollection?

转载 作者:行者123 更新时间:2023-12-04 16:08:19 25 4
gpt4 key购买 nike

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

但是真的很奇怪,集合中的几乎所有容器都实现了ICollection,除了HashSet仅实现了ICollection<T>之外...

我已经 checkout 了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

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

最佳答案

当没有ICollection提供更高的类型安全性时,ICollection<T>的功能已不如.NET 1.1有用。很少有人可以有效地使用ICollection而不能有效地使用ICollection<T>,通常可以提高效率和/或类型安全,尤其是当人们为那些可能希望对不同元素类型的集合做某事的情况编写通用方法时,尤其如此。

但这引出了一个问题,为什么List<T>之类的东西确实实现了ICollection。但是,在.NET 2.0中引入List<T>时,所有旧代码都使用ICollectionArrayList,而不是ICollection<T>List<T>。升级代码以使用List<T>而不是ArrayList可能会很痛苦,特别是如果这意味着必须立即更改ICollection的所有用法,则使用ICollection<T>会很麻烦,或者甚至更糟,因为使用了List<T>的方法被击中了也被其他非通用集合所打击,因此每种方法都需要使用该方法的版本。实现ICollection可以使人们更加零碎地利用通用集合,从而简化了升级路径。

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

关于.net - 为什么HashSet <T>不实现ICollection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31273003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com