如何从 C# 中数组中访问元素?


首先,定义并初始化一个数组 −

int[] p = new int[3] {99, 92, 95};

现在,显示数组元素 −

for (j = 0; j < 3; j++ ) {
   Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
}

要访问任何元素,只需包含该元素的索引,如下所示 −

p[2];

上面是访问第 3 个元素。

下面让我们来看完整的代码 −

示例

using System;

namespace Program {
   class Demo {
      static void Main(string[] args) {
         int[] p = new int[3] {99, 92, 95};
         int j;

         for (j = 0; j < 3; j++ ) {
            Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
         }

         // access
         int e = p[2];
         Console.WriteLine("Product 3rd price: "+e);

         Console.ReadKey();
      }
   }
}

更新于: 2020 年 6 月 21 日

794 浏览

开始你的 职业生涯

完成课程后获得认证

开始吧
广告
© . All rights reserved.