多维数组的声明
在声明时,必须指定数组的长度,格式为 type [lenght ,lenght ,lengh, … ]
int [,] test1 = new int [3,3];
或声明时即赋值,由系统推断长度
int [,] test1 = {{1,2,3},{1,2,3},{1,2,3},};
交错数组的声明
声明时,至少需要指定第一维的长度,格式为 type [ ] [ ] [ ] …
int [][] test1 = new int[5][];int [][] test1 = new int[][]; //注意,此的声明方式是错的
或者声明时即赋值,由系统推断长度
int [][] test1 = {new int[] {1,2,3,4},new int[] {1,2,3},new int[] {1,2}};
多维数组与交错数组 二者的相同、区别
两者声明时,都必须指定长度,多维数组必须指定每一维的长度,而交错数组需要至少需要指定第一维的长度。
多维数组声明时,符号是这样的 [ , , , , ],逗号在 方括号 [ ] 中,每一维长度用逗号分隔。而交错数组每一维独立在 [ ]中
当你想指定数组长度时,只能在等号右侧指定,int [,] test1 = new int [3,3] 是正确的 ;int [6,4] test1 = new int [6,4] 是错误的;
下面以代码形式说明
大小不一致的多维数组会发生错误
int [,] test1 = {{1,2,3,4},{1,2,3},{1,2}}; //这样是错的,长度必须一致
int [,] test1 = new int [4,5] {{1,2,3,4,5},{1,2,3},{1,2,3}}; //这样也是错误的,长度必须一致,必须为每一个位置赋值
这一点C#与C语言有所区别,C语言可以不全赋值,没有赋值的位置系统默认为0。
下面的方法是正确的
int [,] test1 = {{1,2,3},{1,2,3},{1,2,3}};
初始化交错数组
上面已经说了声明一个交错数组的方法
int [][] test1 = {new int[] {1,2,3,4}, //new int[4] {1,2,3,4}new int[] {1,2,3}, //new int[3] {1,2,3}new int[] {1,2}};
注意,在里面有 **new int[],这正是交错数组的特性。**交错数组是由数组构成的数组,交错数组要求为内部的每个数组都创建实例。
即交错数组的每一维都是一个实例,每一个实例为一个数组。
数组的长度是固定的
无论多维数组还是交错数组,长度都是固定的,不能随意改变。
获取数组的长度
使用 对象.Length 获取数组的长度,需要注意的是,多维数组的长度是每一维相乘,即元素总个数。
int [,] test1 = {{1,2,3},{1,2,3},{1,2,3}};Console.WriteLine(test1.Length);//输出为 9
而交错数组的长度则是“内部组成的数组的个数”,例如
int [][] test1 = {new int[] {1,2,3},new int[] {1,2,3},new int[] {1,2,3},};Console.WriteLine(test1.Length); //输出为 3
