当然,您需要数组来管理可变结构的集合,如果没有这些结构,我们将如何处理。
struct EvilMutableStruct { public double X; } // don't do this
EvilMutableStruct[] myArray = new EvilMutableStruct[1];
myArray[0] = new EvilMutableStruct()
myArray[0].X = 1; // works, this modifies the original struct
List<EvilMutableStruct> myList = new List<EvilMutableStruct>();
myList.Add(new EvilMutableStruct());
myList[0].X = 1; // does not work, the List will return a *copy* of the struct
(请注意,在某些情况下,需要一个可变结构的数组,但是通常,数组中可变结构与其他集合的这种不同行为是应避免的错误来源)
更严重的是,如果要通过reference传递元素,则需要一个数组。即
Interlocked.Increment(ref myArray[i]); // works
Interlocked.Increment(ref myList[i]); // does not work, you can't pass a property by reference
这对于无锁线程安全代码很有用。
如果您想快速有效地使用默认值初始化固定大小的集合,则需要一个数组。
double[] myArray = new double[1000]; // contains 1000 '0' values
// without further initialisation
List<double> myList = new List<double>(1000) // internally contains 1000 '0' values,
// since List uses an array as backing storage,
// but you cannot access those
for (int i =0; i<1000; i++) myList.Add(0); // slow and inelegant
(请注意,有可能实现List的构造函数执行相同的操作,只是c#不提供此功能)
如果您想有效地复制集合的一部分,则需要一个数组
Array.Copy(array1, index1, array2, index2, length) // can't get any faster than this
double[,] array2d = new double[10,100];
double[] arraySerialized = new double[10*100];
Array.Copy(array2d, 0, arraySerialized, 0, arraySerialized.Length);
// even works for different dimensions
(同样,这也可以为List实现,但是此功能在c#中不存在)
List<T>