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을 제공합니다.