如何访问 C# 中矩形数组中的元素?


要访问矩形数组中的元素,只需要设置要从中获取元素的索引即可。多维数组也称为矩形数组 −

a[0,1]; // second element

以下示例展示了如何在 C# 中使用矩形数组以及访问元素 −

示例

using System;

namespace Demo {

   class Program {
      static void Main(string[] args) {

         int[,] a = new int[3, 3];
         a[0,0]= 10;
         a[0,1]= 20;
         a[0,2]= 30;
         a[1,0]= 40;
         a[1,1]= 50;
         a[1,2]= 60;
         a[2,0]= 70;
         a[2,1]= 80;

         // accessing element
         a[2,2]= 90;

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

         int ele = a[0,1];
         Console.WriteLine("Second element: "+ele);

         Console.ReadKey();
      }
   }
}

更新时间: 2020-06-21

205 次浏览

开启你的职业生涯生涯

完成课程,获得认证

开始学习
广告
© . All rights reserved.