理解 C# 中的数组 IndexOutofBoundsException
csharpprogrammingserver side programming更新于 2025/9/8 11:22:17
Java 中会发生数组 IndexOutofBoundsException。C# 中与之对应的异常是 IndexOutOfRangeException。
当 Index 超出数组边界时,会发生 IndexOutOfRangeException。
示例
using System;
using System.IO;
using System.Collections.Generic;
namespace Demo {
class Program {
static void Main(string[] args) {
int[] arr = new int[3];
arr[0] = 5;
arr[1] = 7;
arr[2] = 8;
arr[4] = 24; // 这显示错误
}
}
}
输出
以下是输出。它显示以下错误 −
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.

