C#多维数组

C#多维数组 首页 / C#入门教程 / 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 } };

看一个多维数组的简单示例,它在声明时初始化数组。

链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-multidimensional-array.html

来源:LearnFk无涯教程网

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

教程推荐

结构思考力 · 透过结构看表达 -〔李忠秋〕

说透数字化转型 -〔付晓岩〕

Flink核心技术与实战 -〔张利兵〕

重学线性代数 -〔朱维刚〕

TensorFlow 2项目进阶实战 -〔彭靖田〕

Web协议详解与抓包实战 -〔陶辉〕

10x程序员工作法 -〔郑晔〕

程序员进阶攻略 -〔胡峰〕

零基础学Python -〔尹会生〕

好记忆不如烂笔头。留下您的足迹吧 :)