C#多维数组
多维数组在C#中也称为矩形数组。它可以是二维的,也可以是三维的。数据以表格形式(行*列)存储,也称为矩阵。
int[,] arr=new int[3,3];//二维数组的声明 int[,,] arr=new int[3,3,3];//3D 数组的声明
C#多维数组示例
看一个用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#多维数组示例: Declaration and initialization at same time
在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 } };
也可以省略新的运算符。
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
祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)
精选教程推荐
👇 以下精选教程可能对您有帮助,拓展您的技术视野
暂无学习笔记,成为第一个分享的人吧!
您的笔记将帮助成千上万的学习者