我只能从 Java 的角度谈谈,但我相信 C# 的工作方式大致相同(如果不是这种情况,请有人纠正我)。
声明和分配数组与在执行的哪个时间点做了什么是有区别的。
当你声明一个数组类型的变量时,它持有一个对象的引用。这不会创建数组对象或为其组件分配空间,只是变量本身。但是初始化器可以创建一个数组,然后它成为变量的初始值。例如:
//only has a variable of firstArray (i.e. doesn't create array,
//therefore array memory not used)
int[] firstArray;
//creates variable secondArray and allocates 4 int
//values to the array
int[] secondArray = { 1, 2, 3, 4 };
参考:(§10.2) JLS
当分配的数组没有特定值时,所有元素都会接收到数组数据类型的默认值(例如,对于布尔值,它将为 false,对于 int 为 0 等)例如:
//Creates an array of 5 Object's which will all
//be null.
Object[] objectArray = new Object[5];
参考:(§8.3) & (§10.2)JLS
这里还有一些多维数组的例子:
//This is allocating an int[] array inside myArray at position [0]
int[][] myArray = { { 1, 2 } };
for (int[] i : myArray)
for (int j : i)
System.out.println(j); //will print 1 then 2;
使用你的一个例子:
//This is declaring a multi-dimensional array of int with a max length of 2
int[][] arr = new int[2][]; //Only declaration, no memory allocation for array components
arr[0] = new int[] {1, 2}; //Allocating memory
arr[1] = new int[] {3, 4}; //Allocating memory
for(int[] i : arr)
for(int j: i)
System.out.println(j); //Will print 1 then 2 then 3 then 4...