泛型和System.Collections

leo*_*ora 8 .net c# generics collections

迁移到.NET 2.0+后,有没有理由继续使用systems.Collections命名空间(除了维护遗留代码)?是否应该始终使用泛型命名空间?

Sco*_*man 12

在大多数情况下,泛型集合的执行速度将比非泛型集合更快,并且可以为您提供强类型集合的好处.比较System.Collections和System.Collections.Generic中可用的集合,您将获得以下"迁移":

    Non-Generic               Generic Equivalent
    ------------------------------------------------------------
    ArrayList                 List<T>
    BitArray                  N/A
    CaseInsensitiveComparer   N/A
    CollectionBase            Collection<T>
    Comparer                  Comparer<T>
    DictionaryBase            Dictionary<TKey,TValue>
    Hashtable                 Dictionary<TKey,TValue>
    Queue                     Queue<T>
    ReadOnlyCollectionBase    ReadOnlyCollection<T>
    SortedList                SortedList<TKey,TValue>
    Stack                     Stack<T>

    DictionaryEntry           KeyValuePair<TKey,TValue>

    ICollection               N/A (use IEnumerable<T> or anything that extends it)
    IComparer                 IComparer<T>
    IDictionary               IDictionary<TKey,TValue>
    IEnumerable               IEnumerable<T>
    IEnumerator               IEnumerator<T>
    IEqualityComparer         IEqualityComparer<T>
    IList                     IList<T>

ICollection是不可变的(没有成员可以更改集合的内容),而ICollection <T>是可变的.这使得接口在名称上相似,而ICollection和IEnumerable <T>相差很小.

从该列表中,唯一没有通用对应的非泛型类是BitArray和CaseInsensitiveComparer.