如何在 C# 中初始化矩形数组?

csharpprogrammingserver side programming更新于 2025/5/25 4:07:17

数组用于存储数据集合,但将数组视为存储在连续内存位置的相同类型变量的集合通常更有用。

多维数组也称为矩形数组。通过为每行指定括号中的值来初始化多维数组。

以下数组有 2 行,每行有 2 列。

int [,] a = new int [2,2] {
{20, 50} , /* 行索引为 0 的初始化程序 */
{15, 45} , /* 行索引为 1 的初始化程序 */
};

让我们看一个例子 −

示例

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         /* 一个有 2 行 2 列的数组*/
         int [,] a = new int [2,2] {
            {20, 50} , /* 行索引为 0 的初始化程序 */
            {15, 45} , /* 索引为 1 的行的初始值设定项 */
         };
         int i, j;

         for (i = 0; i < 2; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }  
         Console.ReadKey();
      }
   }
}

相关文章