Tip16 元素數量可變的情況下不應使用數組
數組一旦被創建,長度就不能改變。如果我們需要一個動態且可變長度的集合,就應該使用ArrayList或List<T>來創建。List<T>是ArrayList的泛型實現,它省去了拆箱和裝箱帶來的開銷。
注:不能肆意對數組指定過大的長度,這會讓數組成爲一個大對象(佔用內存超過85000字節的對象),大對象在回收過程中會帶來效率很低的問題。
如果一定要動態改變數組的長度,一種方法是將數組轉換爲ArrayList或List<T>:
int[] iArr = { 0, 1, 2, 3, 4, 5, 6 };
ArrayList arrayListInt = ArrayList.Adapter(iArr);
arrayListInt.Add(7);
List<int> listInt = iArr.ToList<int>();
listInt.Add(7);
另一種方法(效率很低):是用數組的複製功能,創建一個名爲ReSize的擴展方法,具體如下:
public static class ClassForExtensions
{
//
public static Array ReSize(this Array array, int newSize)
{
Type t = array.GetType().GetElementType();
Array newArray = Array.CreateInstance(t, newSize);
Array.Copy(array, 0, newArray, 0, Math.Min(array.Length, newSize));
return newArray;
}
}
調用如下:
//調用:
int[] iArr = { 0, 1, 2, 3, 4, 5, 6 };
iArr = (int[])iArr.ReSize(10);
最後建議——在元素數量可變的情況下不應使用數組