C# 容器可以分為無Generic時代 和 Generic時代。Generic是C# 2.0時的產物。
在System.Collections.Generic,也就是泛型命名空間出現以前。常用的是System.Collections 命名空間下的容器,包括ArrayList,Stack, SortedList, Queue等等。這些容器有一個共同特點:其存儲的元素都是object。這就意味着,比如ArrayList,它可以同時存放各種類型的數據,因為所有的類型都會轉化為object存儲,訪問元素時會自動提出數據。這樣的過程,我們稱其為“裝箱”和“拆箱”(boxing and unboxing)。
因此,System.Collections中的容器好處在於:不是嚴格類型的,可以放不同類型的值。壞處在於:因為對存放數據沒有類型要求,所以不是類型安全的;另外,裝箱和拆箱會是一個很耗費時間的工作。
arraylist vs List<> in c#
http://stackoverflow.com/questions/2309694/arraylist-vs-list-in-c-sharp
List<T>
is a generic class. It supports storing values of a specific type without casting to or from object
(which would have incurred boxing/unboxing overhead when T
is a value type in the ArrayList
case). ArrayList
simply stores object
references. As a generic collection, it implements the generic IEnumerable<T>
interface and can be used easily in LINQ (without requiring any Cast
or OfType
call).
ArrayList
belongs to the days that C# didn't have generics. It's deprecated in favor of List<T>
. You shouldn't use ArrayList
in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.
引申出generic。
引申出LINQ,
List<T> 等屬於 Generics,Arraylist等屬於早期的容器
The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface by using an array whose size is dynamically increased as required.
我們都知道List<T>
的Add
是O(1)的操作,但之所以它是O(1),是因為它的“擴容”操作被均攤了(amortized),但每次擴容時其實還是需要復制所有元素,次數越少越好
http://blog.zhaojie.me/2013/01/think-in-detail-why-its-o-1.html
In deciding whether to use the List<T> or ArrayList class, both of which have similar functionality, remember that the List<T> class performs better in most cases and is type safe. If a reference type is used for type T of the List<T> class, the behavior of the two classes is identical. However, if a value type is used for type T, you need to consider implementation and boxing issues.
來自http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
衍生出裝箱和拆箱。。。
Benefits of Generics
http://msdn.microsoft.com/en-us/library/b5bx6xee.aspx
LINQ Query
http://www.cnblogs.com/greenerycn/archive/2010/10/22/linq_intro.html