在学习多维数组之前,请确保您了解 C# 中的一维数组。
在多维数组中,数组的每个元素也是一个数组。例如,
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };
这里,x 是一个多维数组,它有两个元素:**{1, 2, 3}** 和 **{3, 4, 5}**。并且,数组的每个元素也是一个包含 **3** 个元素的数组。
C# 中的二维数组
二维数组由一维数组作为其元素组成。它可以表示为一个具有特定行数和列数的表。

这里,行 **{1, 2, 3}** 和 **{3, 4, 5}** 是二维数组的元素。
1. 二维数组声明
以下是在 C# 中声明二维数组的方法。
int[ , ] x = new int [2, 3];
这里,x 是一个包含 **2** 个元素的二维数组。并且,每个元素也是一个包含 **3** 个元素的数组。
因此,总共该数组可以存储 **6** 个元素 (**2 * 3**)。
注意:单个逗号 [ , ] 表示该数组是二维的。
2. 二维数组初始化
在 C# 中,我们可以在声明时初始化数组。例如,
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };
这里,x 是一个二维数组,包含两个元素 {1, 2, 3}
和 {3, 4, 5}
。我们可以看到数组的每个元素也是一个数组。
我们也可以在初始化时指定行数和列数。例如,
int [ , ] x = new int[2, 3]{ {1, 2, 3}, {3, 4, 5} };
3. 访问二维数组中的元素
我们使用索引号来访问二维数组中的元素。例如,
// a 2D array
int[ , ] x = { { 1, 2 ,3}, { 3, 4, 5 } };
// access first element from first row
x[0, 0]; // returns 1
// access third element from second row
x[1, 2]; // returns 5
// access third element from first row
x[0, 2]; // returns 3

示例:C# 二维数组
using System;
namespace MultiDArray {
class Program {
static void Main(string[] args) {
//initializing 2D array
int[ , ] numbers = {{2, 3}, {4, 5}};
// access first element from the first row
Console.WriteLine("Element at index [0, 0] : "+numbers[0, 0]);
// access first element from second row
Console.WriteLine("Element at index [1, 0] : "+numbers[1, 0]);
}
}
}
输出
Element at index [0, 0] : 2 Element at index [1, 0] : 4
在上面的示例中,我们创建了一个名为 numbers 的二维数组,其中包含行 **{2, 3}** 和 **{4, 5}**。
这里,我们使用索引号来访问二维数组的元素。
numbers[0, 0]
- 访问第一行的第一个元素 (**2**)numbers[1, 0]
- 访问第二行的第一个元素 (**4**)
更改数组元素
我们也可以更改二维数组的元素。要更改元素,只需为该特定索引赋一个新值即可。例如,
using System;
namespace MultiDArray {
class Program {
static void Main(string[] args) {
int[ , ] numbers = {{2, 3}, {4, 5}};
// old element
Console.WriteLine("Old element at index [0, 0] : "+numbers[0, 0]);
// assigning new value
numbers[0, 0] = 222;
// new element
Console.WriteLine("New element at index [0, 0] : "+numbers[0, 0]);
}
}
}
输出
Old element at index [0, 0] : 2 New element at index [0, 0] : 222
在上面的示例中,索引 **[0, 0]** 的初始值为 **2**。请注意这一行:
// assigning new value
numbers[0, 0] = 222;
这里,我们在索引 **[0, 0]** 处赋了一个新值 **222**。现在,索引 **[0, 0]** 的值从 **2** 更改为 **222**。
使用循环迭代 C# 数组
using System;
namespace MultiDArray {
class Program {
static void Main(string[] args) {
int[ , ] numbers = { {2, 3, 9}, {4, 5, 9} };
for(int i = 0; i < numbers.GetLength(0); i++) {
Console.Write("Row "+ i+": ");
for(int j = 0; j < numbers.GetLength(1); j++) {
Console.Write(numbers[i, j]+" ");
}
Console.WriteLine();
}
}
}
}
输出
Row 0: 2 3 9 Row 1: 4 5 9
在上面的示例中,我们使用 嵌套 for 循环 来遍历二维数组的元素。这里,
numbers.GetLength(0)
- 返回二维数组的行数numbers.GetLength(1)
- 返回行中的元素数量
**注意**:我们也可以创建三维数组。从技术上讲,三维数组是一个以多个二维数组作为其元素的数组。例如,
int[ , , ] numbers = { { { 1, 3, 5 }, { 2, 4, 6 } },
{ { 2, 4, 9 }, { 5, 7, 11 } } };
这里,[ , , ]
(两个逗号) 表示三维数组。