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...inF#) 中的语句 (或For EachVisual Basic) 中的语句 (来循环访问数组中的所有元素。

  • 尝试将数组元素分配给另一个数组,该数组的维度不够,且元素少于原始数组。 以下示例尝试将数组中的 value1 最后一个元素分配给数组中的 value2 同一元素。 但是, value2 数组的维度不正确,没有 6 个元素而不是 7 个元素。 因此,分配将引发异常 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 互操作返回,尽管它们不符合 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#) 中使用语句 (、for...inF#) 中的语句 (或For EachVisual Basic) 中的语句 (时,通常会发生foreach此问题。 以下示例演示了该问题。

    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 个对象读取、从多个线程写入同 StreamWriterHashtable 对象或从不同线程枚举对象等操作,如果无法以线程安全的方式访问对象,则可能会引发 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

  • 斯莱姆<type>

IndexOutOfRangeException 使用具有值0x80131508的 HRESULT COR_E_INDEXOUTOFRANGE。

构造函数

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)

适用于

另请参阅