共用方式為


IndexOutOfRangeException 類別

定義

嘗試使用陣列或集合以外索引來存取陣列或集合項目時所擲回的例外狀況。

public ref class IndexOutOfRangeException sealed : Exception
public ref class IndexOutOfRangeException sealed : SystemException
public sealed class IndexOutOfRangeException : Exception
public sealed class IndexOutOfRangeException : SystemException
[System.Serializable]
public sealed class IndexOutOfRangeException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class IndexOutOfRangeException : SystemException
type IndexOutOfRangeException = class
    inherit Exception
type IndexOutOfRangeException = class
    inherit SystemException
[<System.Serializable>]
type IndexOutOfRangeException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type IndexOutOfRangeException = class
    inherit SystemException
Public NotInheritable Class IndexOutOfRangeException
Inherits Exception
Public NotInheritable Class IndexOutOfRangeException
Inherits SystemException
繼承
IndexOutOfRangeException
繼承
IndexOutOfRangeException
屬性

備註

IndexOutOfRangeException當使用不正確索引來存取陣列或集合的成員,或從緩衝區中的特定位置讀取或寫入時,就會擲回例外狀況。 這個例外狀況繼承自 類別, Exception 但不會新增唯一的成員。

一般而言, IndexOutOfRangeException 因為開發人員錯誤而擲回例外狀況。 您應該診斷錯誤的原因並更正程式碼,而不是處理例外狀況。 最常見的錯誤原因如下:

  • 忘記集合或以零起始陣列的上限小於其成員或元素數目,如下列範例所示。

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<Char> characters = new List<Char>();
          characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } );
          for (int ctr = 0; ctr <= characters.Count; ctr++)
             Console.Write("'{0}'    ", characters[ctr]);
       }
    }
    // The example displays the following output:
    //    'a'    'b'    'c'    'd'    'e'    'f'
    //    Unhandled Exception:
    //    System.ArgumentOutOfRangeException:
    //    Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at Example.Main()
    
    let characters = ResizeArray()
    characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |])
    
    for i = 0 to characters.Count do
        printf $"'{characters[i]}'    "
    // The example displays the following output:
    //    'a'    'b'    'c'    'd'    'e'    'f'
    //    Unhandled Exception:
    //    System.ArgumentOutOfRangeException:
    //    Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at <StartupCode$fs>.main@()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim characters As New List(Of Char)()
          characters.InsertRange(0, { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c} )
          For ctr As Integer = 0 To characters.Count
             Console.Write("'{0}'    ", characters(ctr))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '    'a'    'b'    'c'    'd'    'e'    'f'
    '    Unhandled Exception: 
    '    System.ArgumentOutOfRangeException: 
    '    Index was out of range. Must be non-negative and less than the size of the collection.
    '    Parameter name: index
    '       at System.Collections.Generic.List`1.get_Item(Int32 index)
    '       at Example.Main()
    

    若要更正錯誤,您可以使用如下所示的程式碼。

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<Char> characters = new List<Char>();
          characters.InsertRange(0, new Char[] { 'a', 'b', 'c', 'd', 'e', 'f' } );
          for (int ctr = 0; ctr < characters.Count; ctr++)
             Console.Write("'{0}'    ", characters[ctr]);
       }
    }
    // The example displays the following output:
    //        'a'    'b'    'c'    'd'    'e'    'f'
    
    let characters = ResizeArray()
    characters.InsertRange(0, [| 'a'; 'b'; 'c'; 'd'; 'e'; 'f' |])
    
    for i = 0 to characters.Count - 1 do
        printf $"'{characters[i]}'    "
    // The example displays the following output:
    //        'a'    'b'    'c'    'd'    'e'    'f'
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim characters As New List(Of Char)()
          characters.InsertRange(0, { "a"c, "b"c, "c"c, "d"c, "e"c, "f"c} )
          For ctr As Integer = 0 To characters.Count - 1
             Console.Write("'{0}'    ", characters(ctr))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '       'a'    'b'    'c'    'd'    'e'    'f'
    

    或者,您可以改 foreach 用 C#) for...in 、F#) 中的 (語句 (,或 For Each Visual Basic) 中的 語句 (,而不是逐一查看陣列中的所有元素。

  • 嘗試將陣列專案指派給另一個尚未適當維度且元素少於原始陣列的陣列。 下列範例會嘗試將陣列中的 value1 最後一個專案指派給陣列中的 value2 相同專案。 不過, value2 陣列的維度不正確為六個,而不是七個元素。 因此,指派會擲回 IndexOutOfRangeException 例外狀況。

    public class Example
    {
       public static void Main()
       {
          int[] values1 = { 3, 6, 9, 12, 15, 18, 21 };
          int[] values2 = new int[6];
    
          // Assign last element of the array to the new array.
          values2[values1.Length - 1] = values1[values1.Length - 1];
       }
    }
    // The example displays the following output:
    //       Unhandled Exception:
    //       System.IndexOutOfRangeException:
    //       Index was outside the bounds of the array.
    //       at Example.Main()
    
    let values1 = [| 3; 6; 9; 12; 15; 18; 21 |]
    let values2 = Array.zeroCreate<int> 6
    
    // Assign last element of the array to the new array.
    values2[values1.Length - 1] <- values1[values1.Length - 1];
    // The example displays the following output:
    //       Unhandled Exception:
    //       System.IndexOutOfRangeException:
    //       Index was outside the bounds of the array.
    //       at <StartupCode$fs>.main@()
    
    Module Example
       Public Sub Main()
          Dim values1() As Integer = { 3, 6, 9, 12, 15, 18, 21 }
          Dim values2(5) As Integer
          
          ' Assign last element of the array to the new array.
          values2(values1.Length - 1) = values1(values1.Length - 1)
       End Sub
    End Module
    ' The example displays the following output:
    '       Unhandled Exception: 
    '       System.IndexOutOfRangeException: 
    '       Index was outside the bounds of the array.
    '       at Example.Main()
    
  • 使用搜尋方法傳回的值,逐一查看從特定索引位置開始的陣列或集合部分。 如果您忘記檢查搜尋作業是否找到相符專案,執行時間會 IndexOutOfRangeException 擲回例外狀況,如本範例所示。

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       static List<int> numbers = new List<int>();
    
       public static void Main()
       {
          int startValue;
          string[] args = Environment.GetCommandLineArgs();
          if (args.Length < 2)
             startValue = 2;
          else
             if (! Int32.TryParse(args[1], out startValue))
                startValue = 2;
    
          ShowValues(startValue);
       }
    
       private static void ShowValues(int startValue)
       {
          // Create a collection with numeric values.
          if (numbers.Count == 0)
             numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} );
    
          // Get the index of a startValue.
          Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue);
          int startIndex = numbers.IndexOf(startValue);
          // Display all numbers from startIndex on.
          for (int ctr = startIndex; ctr < numbers.Count; ctr++)
             Console.Write("    {0}", numbers[ctr]);
       }
    }
    // The example displays the following output if the user supplies
    // 7 as a command-line parameter:
    //    Displaying values greater than or equal to 7:
    //
    //    Unhandled Exception: System.ArgumentOutOfRangeException:
    //    Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at System.Collections.Generic.List`1.get_Item(Int32 index)
    //       at Example.ShowValues(Int32 startValue)
    //       at Example.Main()
    
    open System
    
    let numbers = ResizeArray()
    
    let showValues startValue =
        // Create a collection with numeric values.
        if numbers.Count = 0 then
            numbers.AddRange [| 2..2..22 |]
    
        // Get the index of a startValue.
        printfn $"Displaying values greater than or equal to {startValue}:"
        let startIndex = numbers.IndexOf startValue
        
        // Display all numbers from startIndex on.
        for i = startIndex to numbers.Count - 1 do
            printf $"    {numbers[i]}"
    
    let startValue =
        let args = Environment.GetCommandLineArgs()
        if args.Length < 2 then
            2
        else
            match Int32.TryParse args[1] with
            | true, v -> v
            | _ -> 2
    
    showValues startValue
    
    // The example displays the following output if the user supplies
    // 7 as a command-line parameter:
    //    Displaying values greater than or equal to 7:
    //
    //    Unhandled Exception: System.ArgumentOutOfRangeException:
    //    Index was out of range. Must be non-negative and less than the size of the collection.
    //    Parameter name: index
    //       at System.Collections.Generic.List`1.get_Item(Int32 index)
    //       at Example.ShowValues(Int32 startValue)
    //       at <StartupCode$fs>.main@()
    
    Imports System.Collections.Generic
    
    Module Example
       Dim numbers As New List(Of Integer)
    
       Public Sub Main()
          Dim startValue As Integer 
          Dim args() As String = Environment.GetCommandLineArgs()
          If args.Length < 2 Then
             startValue = 2
          Else
             If Not Int32.TryParse(args(1), startValue) Then
                startValue = 2
             End If   
          End If
          ShowValues(startValue)
       End Sub
       
       Private Sub ShowValues(startValue As Integer)   
          ' Create a collection with numeric values.
          If numbers.Count = 0 Then 
             numbers.AddRange( { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} )
          End If   
          ' Get the index of a particular number, in this case 7.
          Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue)
          Dim startIndex As Integer = numbers.IndexOf(startValue)
          ' Display all numbers from startIndex on.
          For ctr As Integer = startIndex To numbers.Count - 1
             Console.Write("    {0}", numbers(ctr))
          Next
       End Sub
    End Module
    ' The example displays the following output if the user supplies
    ' 7 as a command-line parameter:
    '    Displaying values greater than or equal to 7:
    '    
    '    Unhandled Exception: System.ArgumentOutOfRangeException: 
    '    Index was out of range. Must be non-negative and less than the size of the collection.
    '    Parameter name: index
    '       at System.Collections.Generic.List`1.get_Item(Int32 index)
    '       at Example.ShowValues(Int32 startValue)
    '       at Example.Main()
    

    在此情況下,當方法找不到相符專案時, List<T>.IndexOf 會傳回 -1,這是不正確索引值。 若要更正此錯誤,請在重複陣列之前檢查搜尋方法的傳回值,如本範例所示。

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       static List<int> numbers = new List<int>();
    
       public static void Main()
       {
          int startValue;
          string[] args = Environment.GetCommandLineArgs();
          if (args.Length < 2)
             startValue = 2;
          else
             if (! Int32.TryParse(args[1], out startValue))
                startValue = 2;
    
          ShowValues(startValue);
       }
    
       private static void ShowValues(int startValue)
       {
          // Create a collection with numeric values.
          if (numbers.Count == 0)
             numbers.AddRange( new int[] { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} );
    
          // Get the index of startValue.
          int startIndex = numbers.IndexOf(startValue);
          if (startIndex < 0) {
             Console.WriteLine("Unable to find {0} in the collection.", startValue);
          }
          else {
             // Display all numbers from startIndex on.
             Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue);
             for (int ctr = startIndex; ctr < numbers.Count; ctr++)
                Console.Write("    {0}", numbers[ctr]);
          }
       }
    }
    // The example displays the following output if the user supplies
    // 7 as a command-line parameter:
    //      Unable to find 7 in the collection.
    
    open System
    open System.Collections.Generic
    
    let numbers = new List<int>()
    
    let showValues startValue =
        // Create a collection with numeric values.
        if numbers.Count = 0 then
            numbers.AddRange [| 2..2..22 |]
    
        // Get the index of startValue.
        let startIndex = numbers.IndexOf startValue
        if startIndex < 0 then
            printfn $"Unable to find {startValue} in the collection."
        else
            // Display all numbers from startIndex on.
            printfn $"Displaying values greater than or equal to {startValue}:"
            for i = startIndex to numbers.Count - 1 do
                printf $"    {numbers[i]}"
    
    let startValue =
        let args = Environment.GetCommandLineArgs()
        if args.Length < 2 then
            2
        else
            match Int32.TryParse args[1] with
            | true, v -> v
            | _ -> 2
    
    showValues startValue
    
    // The example displays the following output if the user supplies
    // 7 as a command-line parameter:
    //      Unable to find 7 in the collection.
    
    Imports System.Collections.Generic
    
    Module Example
       Dim numbers As New List(Of Integer)
    
       Public Sub Main()
          Dim startValue As Integer 
          Dim args() As String = Environment.GetCommandLineArgs()
          If args.Length < 2 Then
             startValue = 2
          Else
             If Not Int32.TryParse(args(1), startValue) Then
                startValue = 2
             End If   
          End If
          ShowValues(startValue)
       End Sub
       
       Private Sub ShowValues(startValue As Integer)   
          ' Create a collection with numeric values.
          If numbers.Count = 0 Then 
             numbers.AddRange( { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22} )
          End If   
          ' Get the index of startValue.
          Dim startIndex As Integer = numbers.IndexOf(startValue)
          If startIndex < 0 Then
             Console.WriteLine("Unable to find {0} in the collection.", startValue)
          Else
             ' Display all numbers from startIndex on.
             Console.WriteLine("Displaying values greater than or equal to {0}:",
                            startValue)
             For ctr As Integer = startIndex To numbers.Count - 1
                Console.Write("    {0}", numbers(ctr))
             Next
          End If
       End Sub
    End Module
    ' The example displays the following output if the user supplies
    '       Unable to find 7 in the collection.
    
  • 嘗試使用或列舉查詢傳回的結果集、集合或陣列,而不需要測試傳回的物件是否有任何有效的資料。

  • 使用計算值來定義要逐一查看的起始索引、結束索引或專案數目。 如果計算的結果未預期,可能會導致 IndexOutOfRangeException 例外狀況。 您應該先檢查程式的邏輯,以計算索引值,並在反覆運算陣列或集合之前驗證值。 下列條件必須全部為 true;否則, IndexOutOfRangeException 會擲回例外狀況:

    • 起始索引必須大於或等於 Array.GetLowerBound 您要逐一查看之陣列的維度,或大於或等於集合的 0。

    • 結束索引不能超過 Array.GetUpperBound 您想要逐一查看之陣列的維度,或不能大於或等於 Count 集合的 屬性。

    • 下列方程式對於您想要逐一查看的陣列維度而言,必須是 true:

      start_index >= lower_bound And start_index + items_to_iterate - 1 <= upper_bound  
      

      針對集合,下列方程式必須是 true:

      start_index >= 0 And start_index + items_to_iterate <= Count  
      

      提示

      陣列或集合的起始索引不能是負數。

  • 假設陣列必須是以零起始的。 不是以零起始 Array.CreateInstance(Type, Int32[], Int32[]) 的陣列可由 方法建立,而且可由 COM Interop 傳回,雖然它們不符合 CLS 規範。 下列範例說明 IndexOutOfRangeException 當您嘗試逐一查看 方法所建立的非以零起始的陣列時,所擲回的 Array.CreateInstance(Type, Int32[], Int32[])

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Array values = Array.CreateInstance(typeof(int), new int[] { 10 },
                                              new int[] { 1 });
          int value = 2;
          // Assign values.
          for (int ctr = 0; ctr < values.Length; ctr++) {
             values.SetValue(value, ctr);
             value *= 2;
          }
    
          // Display values.
          for (int ctr = 0; ctr < values.Length; ctr++)
             Console.Write("{0}    ", values.GetValue(ctr));
       }
    }
    // The example displays the following output:
    //    Unhandled Exception:
    //    System.IndexOutOfRangeException: Index was outside the bounds of the array.
    //       at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
    //       at System.Array.SetValue(Object value, Int32 index)
    //       at Example.Main()
    
    open System
    
    let values = 
        Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |])
    let mutable value = 2
    // Assign values.
    for i = 0 to values.Length - 1 do
        values.SetValue(value, i)
        value <- value * 2
    
    // Display values.
    for i = 0 to values.Length - 1 do
        printf $"{values.GetValue i}    "
    
    // The example displays the following output:
    //    Unhandled Exception:
    //    System.IndexOutOfRangeException: Index was outside the bounds of the array.
    //       at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
    //       at System.Array.SetValue(Object value, Int32 index)
    //       at <StartupCode$fs>.main@()
    
    Module Example
       Public Sub Main()
          Dim values = Array.CreateInstance(GetType(Integer), { 10 }, { 1 })
          Dim value As Integer = 2
          ' Assign values.
          For ctr As Integer = 0 To values.Length - 1
             values(ctr) = value
             value *= 2
          Next
          
          ' Display values.
          For ctr As Integer = 0 To values.Length - 1
             Console.Write("{0}    ", values(ctr))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: 
    '    System.IndexOutOfRangeException: Index was outside the bounds of the array.
    '       at System.Array.InternalGetReference(Void* elemRef, Int32 rank, Int32* pIndices)
    '       at System.Array.SetValue(Object value, Int32 index)
    '       at Microsoft.VisualBasic.CompilerServices.NewLateBinding.ObjectLateIndexSetComplex(Obje
    '    ct Instance, Object[] Arguments, String[] ArgumentNames, Boolean OptimisticSet, Boolean RV
    '    alueBase)
    '       at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object Instance,
    '    Object[] Arguments, String[] ArgumentNames)
    '       at Example.Main()
    

    若要更正錯誤,如下列範例所示,您可以呼叫 GetLowerBound 方法,而不是假設陣列的起始索引。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Array values = Array.CreateInstance(typeof(int), new int[] { 10 },
                                              new int[] { 1 });
          int value = 2;
          // Assign values.
          for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++) {
             values.SetValue(value, ctr);
             value *= 2;
          }
    
          // Display values.
          for (int ctr = values.GetLowerBound(0); ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}    ", values.GetValue(ctr));
       }
    }
    // The example displays the following output:
    //        2    4    8    16    32    64    128    256    512    1024
    
    open System
    
    let values = 
        Array.CreateInstance(typeof<int>, [| 10 |], [| 1 |])
    let mutable value = 2
    // Assign values.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        values.SetValue(value, i)
        value <- value * 2
    
    // Display values.
    for i = values.GetLowerBound 0 to values.GetUpperBound 0 do
        printf $"{values.GetValue i}    "
    // The example displays the following output:
    //        2    4    8    16    32    64    128    256    512    1024
    
    Module Example
       Public Sub Main()
          Dim values = Array.CreateInstance(GetType(Integer), { 10 }, { 1 })
          Dim value As Integer = 2
          ' Assign values.
          For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
             values(ctr) = value
             value *= 2
          Next
          
          ' Display values.
          For ctr As Integer = values.GetLowerBound(0) To values.GetUpperBound(0)
             Console.Write("{0}    ", values(ctr))
          Next
       End Sub
    End Module
    ' The example displays the following output:
    '       2    4    8    16    32    64    128    256    512    1024
    

    請注意,當您呼叫 GetLowerBound 方法以取得陣列的起始索引時,也應該呼叫 Array.GetUpperBound(Int32) 方法以取得其結束索引。

  • 混淆數值陣列或集合中該索引處的索引和值。 此問題通常是在 C# ) 中使用 foreach 語句 (、 for...in F#) 中的 語句 (,或 For Each Visual Basic) 中的 語句 (時發生。 下面範例會說明此問題。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          // Generate array of random values.
          int[] values = PopulateArray(5, 10);
          // Display each element in the array.
          foreach (var value in values)
             Console.Write("{0}   ", values[value]);
       }
    
       private static int[] PopulateArray(int items, int maxValue)
       {
          int[] values = new int[items];
          Random rnd = new Random();
          for (int ctr = 0; ctr < items; ctr++)
             values[ctr] = rnd.Next(0, maxValue + 1);
    
          return values;
       }
    }
    // The example displays output like the following:
    //    6   4   4
    //    Unhandled Exception: System.IndexOutOfRangeException:
    //    Index was outside the bounds of the array.
    //       at Example.Main()
    
    open System
    
    let populateArray items maxValue =
        let rnd = Random()
        [| for i = 0 to items - 1 do
            rnd.Next(0, maxValue + 1) |]
    
    // Generate array of random values.
    let values = populateArray 5 10
    // Display each element in the array.
    for value in values do
        printf $"{values[value]}   "
    
    // The example displays output like the following:
    //    6   4   4
    //    Unhandled Exception: System.IndexOutOfRangeException:
    //    Index was outside the bounds of the array.
    //       at <StartupCode$fs>.main@()
    
    Module Example
       Public Sub Main()
          ' Generate array of random values.
          Dim values() As Integer = PopulateArray(5, 10)
          ' Display each element in the array.
          For Each value In values
             Console.Write("{0}   ", values(value))
          Next
       End Sub
       
       Private Function PopulateArray(items As Integer, 
                                      maxValue As Integer) As Integer()
          Dim values(items - 1) As Integer
          Dim rnd As New Random()
          For ctr As Integer = 0 To items - 1
             values(ctr) = rnd.Next(0, maxValue + 1)   
          Next    
          Return values                                                      
       End Function
    End Module
    ' The example displays output like the following:
    '    6   4   4
    '    Unhandled Exception: System.IndexOutOfRangeException: 
    '    Index was outside the bounds of the array.
    '       at Example.Main()
    

    反復專案建構會傳回陣列或集合中的每個值,而不是其索引。 若要消除例外狀況,請使用此程式碼。

    using System;
    
    public class Example
    {
       public static void Main()
       {
          // Generate array of random values.
          int[] values = PopulateArray(5, 10);
          // Display each element in the array.
          foreach (var value in values)
             Console.Write("{0}   ", value);
       }
    
       private static int[] PopulateArray(int items, int maxValue)
       {
          int[] values = new int[items];
          Random rnd = new Random();
          for (int ctr = 0; ctr < items; ctr++)
             values[ctr] = rnd.Next(0, maxValue + 1);
    
          return values;
       }
    }
    // The example displays output like the following:
    //        10   6   7   5   8
    
    open System
    
    let populateArray items maxValue =
        let rnd = Random()
        [| for i = 0 to items - 1 do
            rnd.Next(0, maxValue + 1) |]
    
    // Generate array of random values.
    let values = populateArray 5 10
    // Display each element in the array.
    for value in values do
        printf $"{value}   "
        
    // The example displays output like the following:
    //        10   6   7   5   8
    
    Module Example
       Public Sub Main()
          ' Generate array of random values.
          Dim values() As Integer = PopulateArray(5, 10)
          ' Display each element in the array.
          For Each value In values
             Console.Write("{0}   ", value)
          Next
       End Sub
       
       Private Function PopulateArray(items As Integer, 
                                      maxValue As Integer) As Integer()
          Dim values(items - 1) As Integer
          Dim rnd As New Random()
          For ctr As Integer = 0 To items - 1
             values(ctr) = rnd.Next(0, maxValue + 1)   
          Next    
          Return values                                                      
       End Function
    End Module
    ' The example displays output like the following:
    '       10   6   7   5   8
    
  • 提供不正確資料 DataView.Sort 行名稱給 屬性。

  • 違反執行緒安全性。 從相同 StreamReader 物件讀取、從多個執行緒寫入相同 StreamWriter 物件,或從不同執行緒列舉 中的 Hashtable 物件,如果物件不是以安全線程的方式存取,可能會擲回 IndexOutOfRangeException 。 此例外狀況通常是間歇性的,因為它依賴競爭條件。

如果索引值不正確或無效,或是操作的陣列大小非預期,使用硬式編碼的索引值來運算元組可能會擲回例外狀況。 若要防止作業擲回 IndexOutOfRangeException 例外狀況,您可以執行下列動作:

  • 使用 C#) 中的foreach語句逐一查看陣列的專案 (, for...in statement (in F#) , or the For Each...下一個建構 (Visual Basic) ,而不是依索引逐一查看元素。

  • 以 方法傳回 Array.GetLowerBound 的索引開始逐一查看專案,並以 方法傳回的 Array.GetUpperBound 索引結尾。

  • 如果您要將某個陣列中的元素指派給另一個陣列,請藉由比較 Array.Length 其屬性,確定目標陣列至少具有與來源陣列相同的元素。

如需執行個體的初始屬性值的清單IndexOutOfRangeException,請參閱IndexOutOfRangeException建構函式。

下列中繼語言 (IL) 指示會擲回 IndexOutOfRangeException

  • ldelem。<type>

  • ldelema

  • stelem。<type>

IndexOutOfRangeException 會使用 HRESULT COR_E_INDEXOUTOFRANGE,其值為 0x80131508。

建構函式

IndexOutOfRangeException()

初始化 IndexOutOfRangeException 類別的新執行個體。

IndexOutOfRangeException(String)

使用指定的錯誤訊息,初始化 IndexOutOfRangeException 類別的新執行個體。

IndexOutOfRangeException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 IndexOutOfRangeException 類別的新執行個體。

屬性

Data

取得鍵值組的集合,這些鍵值組會提供關於例外狀況的其他使用者定義資訊。

(繼承來源 Exception)
HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。

(繼承來源 Exception)
HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。

(繼承來源 Exception)
InnerException

取得造成目前例外狀況的 Exception 執行個體。

(繼承來源 Exception)
Message

取得描述目前例外狀況的訊息。

(繼承來源 Exception)
Source

取得或設定造成錯誤的應用程式或物件的名稱。

(繼承來源 Exception)
StackTrace

取得呼叫堆疊上即時運算框架的字串表示。

(繼承來源 Exception)
TargetSite

取得擲回目前例外狀況的方法。

(繼承來源 Exception)

方法

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 Exception

(繼承來源 Exception)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetObjectData(SerializationInfo, StreamingContext)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfo

(繼承來源 Exception)
GetType()

取得目前執行個體的執行階段類型。

(繼承來源 Exception)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

建立並傳回目前例外狀況的字串表示。

(繼承來源 Exception)

事件

SerializeObjectState
已過時。

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。

(繼承來源 Exception)

適用於

另請參閱