数组上的IndexOutOfRangeException

Ama*_*wal -3 c# arrays

int[] arr=new int[10]{1,21,32,43,54,65,76,87,98,10};

foreach(var i in arr)
{
   Console.WriteLine("Elements [{0}]:{1}",arr[i],i);              
}
Run Code Online (Sandbox Code Playgroud)

我希望输出像

element[0]: 1
element[1]: 21
...
element[9]: 10 
Run Code Online (Sandbox Code Playgroud)

foreach仅使用,但我收到此错误:

未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围.在Exercise1.Main()<0x41e47d70 + 0x0008c> in:0 [错误]致命未处理的异常:System.IndexOutOfRangeException:索引超出了数组的范围.在Exercise1.Main()<0x41e47d70 + 0x0008c> in:0

fub*_*ubo 5

i它不是索引,它是它的元素.在循环的第二次迭代中,您尝试访问Console.WriteLine("Elements [{0}]:{1}",arr[21],21)不存在的索引21

改变for循环

int[] arr = new int[10] { 1, 21, 32, 43, 54, 65, 76, 87, 98, 10 };

for (int i =0;i< arr.Length;i++)
{
    Console.WriteLine("Elements [{0}]:{1}",i ,arr[i]);
}
Run Code Online (Sandbox Code Playgroud)