多维数组在C#中也称为矩形数组。它可以是二维的,也可以是三维的。数据以表格形式(行*列)存储,也称为矩阵。
要创建多维数组,无涯教程需要在方括号中使用逗号。例如:
int[,] arr=new int[3,3];//二维数组的声明 int[,,] arr=new int[3,3,3];//3D 数组的声明
看一个用C#编写的多维数组的简单示例,它声明、初始化和遍历二维数组。
using System; public class MultiArrayExample { public static void Main(string[] args) { int[,] arr=new int[3,3];//declaration of 2D array arr[0,1]=10;//initialization arr[1,2]=20; arr[2,0]=30; //traversal for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ Console.Write(arr[i,j]+" "); } Console.WriteLine();//new line at each row } } }
输出:
0 10 0 0 0 20 30 0 0
在C#While声明中有3种初始化多维数组的方法。
int[,] arr = new int[3,3]= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
可以省略数组大小。
int[,] arr = new int[,]{ { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
也可以省略新的运算符。
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-multidimensional-array.html
来源:LearnFk无涯教程网
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
看一个多维数组的简单示例,它在声明时初始化数组。
using System; public class MultiArrayExample { public static void Main(string[] args) { int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };//declaration and initialization //traversal for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ Console.Write(arr[i,j]+" "); } Console.WriteLine();//new line at each row } } }
输出:
1 2 3 4 5 6 7 8 9
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)