Collection是無序的,比如一大群人在廣場上,你不可能說某某人是第一個,某某人是第二個
List是有序的,比如一群人從高到矮排了隊,你就能說這人是第一個,這人是最后一個
因此Collection是沒有index索引,沒有InsertAt等方法的
Collection接口中各元素對象之間沒有指定的順序,允許有重復元素和多個null元素對象,即:類中元素無法實現排序 List接口中各元素對象之間 有 指定的順序,允許有重復元素和多個null元素對象,即:類中元素 可以 實現排序 搜到的,希望有幫助
在C# .net 2.0 庫中,集合類就是在System、System.Collections、System.Collections.Generic和 System.Collections.ObjectModel命名空間下的類,包括Collection, KeyedCollection, ReadOnlyCollection, List, Array,Stack, Queue和ArrayList。
下面是Collection<T>, List<T>和ArrayList三個類的區別
1. List是用來在高性能環境下的類,Collection是為了擴展
使用Collection,開發人員可以重寫ClearItems, InsertItem, RemoveItem 和SetItem, 因為它們是protected virtual類型的,而List<T>卻沒有這些擴展。
2. 實現的接口不一樣
Collection<T>實現IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable
List<T>實現IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollectionIEnumerable
ArrayList實現IList, ICollection, IEnumerable, ICloneable
IList<T>,ICollection<T>, IEnumerable<T>和IList, ICollection, IEnumerable是完全不同的,前者用於范型,
view plain public interface IList<T> : ICollection<T>, IEnumerable<T>IEnumerable { T Item; abstract int IndexOf(T item); abstract void Insert(int index, T item); abstract void RemoveAt(int index); } public interface IList : ICollectionIEnumerable { bool IsFixedSize; bool IsReadOnly; object Item; abstract int Add(object value); abstract void Clear(); abstract bool Contains(object value); abstract int IndexOf(object value); abstract void Insert(int index, object value); abstract void Remove(object value); abstract void RemoveAt(int index); }
另一方面,Collection<T>和List<T>也實現了IList, ICollectionIEnumerable,說明這兩個類比ArrayList提供了更多的方法。
3. 范型與非范型的區別
ArrayList是非范型類,如此,這個集合可以包含不同類型成員,我們可以看到,Add方法是Add(Object obj),所以這是一個對象雜陳的類。使用這個類進行操作時,IndexOf,Remove等都要使用類的Equals和HashCode,所以如果是自 己實現的類,一定要判斷是否同一類型。
比如這個類是 TestType
view plain public override bool Equals(Object obj) { TestType tType = obj as TestType; if (tType == null) { return false; } //其它業務代碼 ... }
總結:
如果有擴展要求,可以考慮使用Collection<T>,如果有性能要求,考慮用List<T>,如果想存放不同類型的對象,使用ArrayList。