我将编写一个库来遍历对象图(类似于某种序列化)。
您需要判断一个对象是否是遍历中的集合,因此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 这是个虫子吗?或者背后有什么原因?
发布于 2019-03-07 15:45:19
当没有提供更好的类型安全性的ICollection时,.NET不再像.NET 1.1那样有用。对于ICollection,人们几乎没有什么能有效地处理ICollection<T>的,这通常具有更高的效率和/或类型安全性,特别是当您编写泛型方法时,您可能希望使用不同元素类型的集合来完成一些事情。
然而,这回避了为什么像List<T>这样的人确实实现了ICollection的问题。但是,当List<T>在.NET 2.0中引入时,所有遗留代码都使用ICollection和ArrayList,而不是ICollection<T>和List<T>。将代码升级到使用List<T>而不是ArrayList可能会很痛苦,特别是如果这意味着必须立即更改它将使用的ICollection的所有用法以使用ICollection<T>,或者更糟糕的是,由于一个方法正在与其他非泛型集合一起命中的List<T>被击中,所以每个方法都需要版本。实现ICollection简化了升级过程,允许人们在如何利用通用集合方面更加零敲碎打。
当HashSet<T>问世时,泛型已经使用了三年,而且之前没有框架提供的非泛型哈希集类型,因此没有那么多升级痛苦,因此支持ICollection的动机也就少了。
https://stackoverflow.com/questions/31273003
复制相似问题