數組
class TestArraysClass { static void Main() { // Declare a single-dimensional array int[] array1 = new int[5]; // Declare and set array element values int[] array2 = new int[] { 1, 3, 5, 7, 9 }; // Alternative syntax int[] array3 = { 1, 2, 3, 4, 5, 6 }; // Declare a two dimensional array int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } }; // Declare a jagged array int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure jaggedArray[0] = new int[4] { 1, 2, 3, 4 }; } }
數組在聲明時必須指定長度
ArryList
ArrayList list1 = new ArrayList(); //新增數據 list1.Add("cde"); list1.Add(5678); //不安全類型 //修改數據 list[2] = 34; //移除數據 list.RemoveAt(0); //插入數據 list.Insert(0, "qwe");
從上面的例子看,在list1中,我們不僅插入了字符串cde,而且插入了數字5678。這樣在ArrayList中插入不同類型的數據是允許的。因為ArrayList會把所有插入其中的數據當作為object類型來處理,在我們使用ArrayList處理數據時,很可能會報類型不匹配的錯誤,也就是ArrayList不是類型安全的。在存儲或檢索值類型時通常發生裝箱和取消裝箱操作,帶來很大的性能耗損。
泛型List
List<string> list = new List<string>(); //新增數據 list.Add(“abc”); //修改數據 list[0] = “def”; //移除數據 list.RemoveAt(0);
如果我們往List集合中插入int數組123,IDE就會報錯,且不能通過編譯。這樣就避免了前面講的類型安全問題與裝箱拆箱的性能問題了。
總結:
數組的容量是固定的,您只能一次獲取或設置一個元素的值,而ArrayList或List<T>的容量可根據需要自動擴充、修改、刪除或插入數據。
數組可以具有多個維度,而 ArrayList或 List< T> 始終只具有一個維度。但是,您可以輕松創建數組列表或列表的列表。特定類型(Object 除外)的數組 的性能優於 ArrayList的性能。 這是因為 ArrayList的元素屬於 Object 類型;所以在存儲或檢索值類型時通常發生裝箱和取消裝箱操作。不過,在不需要重新分配時(即最初的容量十分接近列表的最大容量),List< T> 的性能與同類型的數組十分相近。
在決定使用 List<T> 還是使用ArrayList 類(兩者具有類似的功能)時,記住List<T> 類在大多數情況下執行得更好並且是類型安全的。如果對List< T> 類的類型T 使用引用類型,則兩個類的行為是完全相同的。但是,如果對類型T使用值類型,則需要考慮實現和裝箱問題。