了解C#中的IndexOutOfRangeException异常
当Index在数组的边界之外时,就会发生这种情况。
让我们来看一个例子。我们声明了一个包含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.
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短