目录
一、定义
首先我们定义这样两个对象
int[,] arr1 = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[][] arr2 = { new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, new int[] { 7, 8, 9 } };
二、维数(秩)
然后编译上面的对象,看看值是怎样的
![C#中int[][]与int[,]的使用与区别](https://www.freexyz.cn/d/file/20230724/1a5617951a0719e7b096ee426e46a02e.jpg)
![C#中int[][]与int[,]的使用与区别](https://www.freexyz.cn/d/file/20230724/8370625f2d7b71ab8cd1822bd9c380d6.jpg)
从上图中和定义 我们应该发现这种int[][]形式的,不应该叫做二维数字,只不过一维数组里包了一维数组,就是在套娃。
其实还有直接数据可以证明,在上述两个对象中有一个叫Rank的属性,可以获取其Array的秩,即维数
![C#中int[][]与int[,]的使用与区别](https://www.freexyz.cn/d/file/20230724/6378b0172a57c1611870b5171736514d.jpg)
看看就知道了
int rank1 = arr1.Rank; int rank2 = arr2.Rank;
结果如下
![C#中int[][]与int[,]的使用与区别](https://www.freexyz.cn/d/file/20230724/d52e6fe2ec49efa41abe1a06aeb4d348.jpg)
很明显了,只有int[,]才是二维数组,int[][]还是一维的。
三、取值赋值
这个两者是差不多的
int num1 = arr1[1, 2]; int num2 = arr2[1][2]; arr1[1, 2] = 10; arr2[2][2] = 10;
四、获取数组长度
对于Array我们有GetLength(int dimension)可以获取长度,其中dimension表示维数int[,]:
int len1 = arr1.GetLength(0); //len1 = 3 int len11 = arr1.GetLength(1); //len11 = 3
但是因为int[][]是一维的,所以我们使用上面的方式
int len2 = arr2.GetLength(0); //len2 = 3 int len22 = arr2.GetLength(1); //越界
会抛出IndexOutOfRangeException:“索引超出了数组界限的异常,这很容易想到。既然是一维的,我们直接获取其Length属性就可以了
//第一层数组长度 int len2 = arr2.Length; //len2 = 3 //因为第一层中对象也是数组,所以取第二层数字长度获取具体的Length int len22 = arr2[0].Length; //len22 = 3
五、遍历
有了维数,遍历就轻松了
///int[,]
for (int i = 0; i < arr1.GetLength(0); i++)
{
for (int j = 0; j < arr1.GetLength(1); j++)
{
//To Do
}
}
///int[][]
for (int i = 0; i < arr1.Length; i++)
{
for (int j = 0; j < arr1[0].Length; j++)
{
//To Do
}
}
六、初始化数据
假设初始化数据[ [1,1,..*n...,1,1], [2,2,..*n...,2,2], [3,3,..*n...,3,3],...*m.... ,[m-1,m-1,..*n...,m-1,m-1], [m,m,..*n...,m,m] ]int[,]
public int[,] InitArray(int m = 0, int n = 0)
{
int[, ] arr = new int[m, n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
arr[i, j] = i + 1;
}
}
return arr;
}
int[][]
public int[,] InitArray(int m = 0, int n = 0)
{
int[][] arr = new int[m][];
for (int i = 0; i < m; i++)
{
int[] curArr = new int[n];
for (int j = 0; j < n; j++)
{
arr[j] = i + 1;
}
arr[i] = curArr;
}
return arr;
}
