C#中Collection,List和ArrayList的區別

來源:互聯網
上載者:User
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
  1. public interface IList<T> : ICollection<T>, IEnumerable<T>IEnumerable  
  2. {  
  3.     T Item;  
  4.     abstract int IndexOf(T item);  
  5.     abstract void Insert(int index, T item);  
  6.     abstract void RemoveAt(int index);  
  7. }  
  8. public interface IList : ICollectionIEnumerable  
  9. {  
  10.     bool IsFixedSize;  
  11.     bool IsReadOnly;  
  12.     object Item;  
  13.     abstract int Add(object value);  
  14.     abstract void Clear();  
  15.     abstract bool Contains(object value);  
  16.     abstract int IndexOf(object value);  
  17.     abstract void Insert(int index, object value);  
  18.     abstract void Remove(object value);  
  19.     abstract void RemoveAt(int index);  
  20. }  

 

另一方面,Collection<T>和List<T>也實現了IList, ICollectionIEnumerable,說明這兩個類比ArrayList提供了更多的方法。

 

3. 範型與非範型的區別

ArrayList是非範型類,如此,這個集合可以包含不同類型成員,我們可以看到,Add方法是Add(Object obj),所以這是一個對象雜陳的類。使用這個類進行操作時,IndexOf,Remove等都要使用類的Equals和HashCode,所以如果是自 己實現的類,一定要判斷是否同一類型。

 

比如這個類是 TestType

 

view plain
  1. public override bool Equals(Object obj)  
  2. {  
  3.     TestType tType = obj as TestType;  
  4.     if (tType == null)  
  5.     {  
  6.         return false;  
  7.     }  
  8.     //其它業務代碼  
  9.     ...  
  10. }  

 

 

總結:

如果有擴充要求,可以考慮使用Collection<T>,如果有效能要求,考慮用List<T>,如果想存放不同類型的對象,使用ArrayList。

 

本文參考了.net 2.0類庫和http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.