理解 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.

更新於: 13-4-2020

121 次瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.