http://blog.csdn.net/cronzb/article/details/6429241
在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。
本文參考了.net 2.0類庫和http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx