如何從 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 瀏覽

開始你的 職業生涯

完成課程後獲得認證

開始吧
廣告