理解 C# 中 IndexOutOfRangeException 异常
当索引超出数组范围时便会发生此异常。
我们看一个示例。我们声明了一个包含 5 个元素且大小设置为 5 的数组。
int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;
现在,我们尝试添加一个扩展了我们数组大小的元素,即
arr[5] = 60;
在上面,我们尝试向第 6 个位置添加元素。
示例
using System; using System.IO; using System.Collections.Generic; namespace Demo { class Program { static void Main(string[] args) { int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; arr[5] = 60; // this shows an error } } }
输出
下面是输出结果。显示了以下错误 −
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
广告