如何在 C# 中使用"foreach"语句访问数组元素
csharpprogrammingserver side programming
要在 foreach 语句中访问数组元素,请使用数字索引。
假设以下是我们的代码。
示例
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n 是一个包含 10 个整数的数组 */ /* 初始化数组 n 的元素 */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* 输出每个数组元素的值 */ 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。