如何在 C# 中使用‘foreach’語句訪問陣列元素


要訪問 foreach 語句中的陣列元素,請使用數字索引。

假設以下是我們程式碼。

示例

 現場演示

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int [] n = new int[10]; /* n is an array of 10 integers */
         /* initialize elements of array n */
         for ( int i = 0; i < 10; i++ ) {
            n[i] = i + 100;
         }
         /* output each array element's value */
         foreach (int j in n ) {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
         }
         Console.WriteLine(n);
         Console.ReadKey();
      }
   }
}

輸出

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
System.Int32[]

現在假設你需要第二個元素。為此,請使用。

int a = n[1];

以上將給出第二個元素,即 101。

更新於: 2020 年 6 月 23 日

118 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.