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 } };

也可以省略新的运算符。

链接: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

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

技术教程推荐

深入浅出区块链 -〔陈浩〕

MongoDB高手课 -〔唐建法(TJ)〕

分布式数据库30讲 -〔王磊〕

深度学习推荐系统实战 -〔王喆〕

etcd实战课 -〔唐聪〕

如何成为学习高手 -〔高冷冷〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

Dubbo源码剖析与实战 -〔何辉〕

手把手带你写一个MiniSpring -〔郭屹〕

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