IndexOutOfRangeException Klasa

Definicja

Wyjątek zgłaszany podczas próby uzyskania dostępu do elementu tablicy lub kolekcji z indeksem, który znajduje się poza jej granicami.

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
Dziedziczenie
IndexOutOfRangeException
Dziedziczenie
IndexOutOfRangeException
Atrybuty

Uwagi

Wyjątek IndexOutOfRangeException jest zgłaszany, gdy nieprawidłowy indeks jest używany do uzyskiwania dostępu do elementu członkowskiego tablicy lub kolekcji albo do odczytu lub zapisu z określonej lokalizacji w buforze. Ten wyjątek dziedziczy z Exception klasy, ale nie dodaje żadnych unikatowych składowych.

Zazwyczaj wyjątek IndexOutOfRangeException jest zgłaszany w wyniku błędu dewelopera. Zamiast obsługiwać wyjątek, należy zdiagnozować przyczynę błędu i poprawić kod. Najczęstsze przyczyny błędu to:

  • Zapominając, że górna granica kolekcji lub tablicy zerowej jest mniejsza niż liczba elementów członkowskich lub elementów, jak pokazano w poniższym przykładzie.

    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()
    

    Aby poprawić błąd, możesz użyć kodu podobnego do poniższego.

    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'
    

    Alternatywnie zamiast iterować wszystkie elementy w tablicy według ich indeksu, można użyć foreach instrukcji (w języku C#), for...in instrukcji (w języku F#) lub For Each instrukcji (w Visual Basic).

  • Próba przypisania elementu tablicy do innej tablicy, która nie została odpowiednio wymiarowana i ma mniej elementów niż oryginalna tablica. Poniższy przykład próbuje przypisać ostatni element w value1 tablicy do tego samego elementu w tablicy value2 . Jednak tablica value2 została nieprawidłowo wymiarowana, aby mieć sześć zamiast siedmiu elementów. W rezultacie IndexOutOfRangeException przypisanie zgłasza wyjątek.

    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()
    
  • Użycie wartości zwracanej przez metodę wyszukiwania w celu iterowania części tablicy lub kolekcji, zaczynając od określonej pozycji indeksu. Jeśli zapomnisz sprawdzić, czy operacja wyszukiwania znalazła dopasowanie, środowisko uruchomieniowe zgłasza IndexOutOfRangeException wyjątek, jak pokazano w tym przykładzie.

    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()
    

    W tym przypadku List<T>.IndexOf metoda zwraca wartość -1, która jest nieprawidłową wartością indeksu, gdy nie można odnaleźć dopasowania. Aby poprawić ten błąd, sprawdź wartość zwracaną metody wyszukiwania przed iterowaniem tablicy, jak pokazano w tym przykładzie.

    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.
    
  • Próba użycia lub wyliczenia zestawu wyników, kolekcji lub tablicy zwróconej przez zapytanie bez testowania, czy zwrócony obiekt ma jakiekolwiek prawidłowe dane.

  • Użycie obliczonej wartości do zdefiniowania indeksu początkowego, indeksu końcowego lub liczby elementów, które mają być iterowane. Jeśli wynik obliczeń jest nieoczekiwany, może to spowodować IndexOutOfRangeException wyjątek. Logikę programu należy sprawdzić podczas obliczania wartości indeksu i weryfikować wartość przed iterowaniem tablicy lub kolekcji. Wszystkie poniższe warunki muszą być spełnione; IndexOutOfRangeException w przeciwnym razie zgłaszany jest wyjątek:

    • Indeks początkowy musi być większy lub równy Array.GetLowerBound wymiarowi tablicy, którą chcesz iterować, lub większej lub równej 0 dla kolekcji.

    • Indeks końcowy nie może przekraczać Array.GetUpperBound wymiaru tablicy, którą chcesz iterować, lub nie może być większy niż lub równy Count właściwości kolekcji.

    • Następujące równanie musi być prawdziwe dla wymiaru tablicy, którą chcesz iterować:

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

      W przypadku kolekcji następujące równanie musi mieć wartość true:

      start_index >= 0 And start_index + items_to_iterate <= Count  
      

      Porada

      Początkowy indeks tablicy lub kolekcji nigdy nie może być liczbą ujemną.

  • Zakładając, że tablica musi być oparta na zerach. Tablice, które nie są oparte na zera, mogą być tworzone przez metodę Array.CreateInstance(Type, Int32[], Int32[]) i mogą być zwracane przez międzyoperacyjności MODELU COM, chociaż nie są zgodne ze specyfikacją CLS. Poniższy przykład ilustruje IndexOutOfRangeException , który jest zgłaszany podczas próby iteracji tablicy niezerowej utworzonej przez metodę 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()
    

    Aby naprawić błąd, jak w poniższym przykładzie, można wywołać GetLowerBound metodę zamiast zakładać, że indeks początkowy tablicy.

    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
    

    Należy pamiętać, że po wywołaniu GetLowerBound metody w celu pobrania indeksu początkowego tablicy należy również wywołać Array.GetUpperBound(Int32) metodę , aby uzyskać jej końcowy indeks.

  • Mylące indeks i wartość w tym indeksie w tablicy liczbowej lub kolekcji. Ten problem występuje zwykle podczas korzystania z instrukcji foreach (w języku C#), for...in instrukcji (w języku F#) lub For Each instrukcji (w Visual Basic). Poniższy przykład ilustruje ten problem.

    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()
    

    Konstrukcja iteracji zwraca każdą wartość w tablicy lub kolekcji, a nie jej indeks. Aby wyeliminować wyjątek, użyj tego kodu.

    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
    
  • Podaj nieprawidłową nazwę kolumny DataView.Sort dla właściwości .

  • Naruszenie bezpieczeństwa wątków. Operacje, takie jak odczytywanie z tego samego obiektu, zapisywanie do tego samego StreamReader StreamWriter obiektu z wielu wątków lub wyliczanie obiektów z Hashtable różnych wątków, mogą zgłaszać wyjątek IndexOutOfRangeException , jeśli obiekt nie jest dostępny w bezpieczny wątkowo sposób. Ten wyjątek jest zwykle sporadycznie, ponieważ opiera się na stanie wyścigu.

Użycie zakodowanych na podstawie zakodowanych wartości indeksu do manipulowania tablicą może zgłosić wyjątek, jeśli wartość indeksu jest nieprawidłowa lub nieprawidłowa, lub jeśli rozmiar tablicy jest manipulowania jest nieoczekiwany. Aby zapobiec zgłaszaniu wyjątku przez operację IndexOutOfRangeException , można wykonać następujące czynności:

  • Iterowanie elementów tablicy przy użyciu instrukcji foreach (w języku C#), for... w instrukcji (w języku F#) lub for each... Następna konstrukcja (w Visual Basic) zamiast iterować elementy według indeksu.

  • Iteruj elementy według indeksu, zaczynając od indeksu zwróconego Array.GetLowerBound przez metodę, a kończąc na indeksie zwróconym przez metodę Array.GetUpperBound .

  • Jeśli przypisujesz elementy w jednej tablicy do innej, upewnij się, że tablica docelowa ma co najmniej tyle elementów, ile jest tablicy źródłowej, porównując ich Array.Length właściwości.

Aby uzyskać listę początkowych wartości właściwości dla wystąpienia IndexOutOfRangeExceptionprogramu , zobacz IndexOutOfRangeException konstruktory.

Następujące instrukcje języka pośredniego (IL) zgłaszają wyjątek IndexOutOfRangeException:

  • ldelem.<type>

  • ldelema

  • stelem.<type>

IndexOutOfRangeException używa COR_E_INDEXOUTOFRANGE HRESULT, która ma wartość 0x80131508.

Konstruktory

IndexOutOfRangeException()

Inicjuje nowe wystąpienie klasy IndexOutOfRangeException.

IndexOutOfRangeException(String)

Inicjuje IndexOutOfRangeException nowe wystąpienie klasy z określonym komunikatem o błędzie.

IndexOutOfRangeException(String, Exception)

Inicjuje nowe wystąpienie IndexOutOfRangeException klasy z określonym komunikatem o błędzie i odwołaniem do wyjątku wewnętrznego, który jest przyczyną tego wyjątku.

Właściwości

Data

Pobiera kolekcję par klucz/wartość, które zapewniają dodatkowe informacje zdefiniowane przez użytkownika dotyczące wyjątku.

(Odziedziczone po Exception)
HelpLink

Pobiera lub ustawia link do pliku pomocy skojarzonego z tym wyjątkiem.

(Odziedziczone po Exception)
HResult

Pobiera lub ustawia HRESULT, zakodowaną wartość liczbową przypisaną do określonego wyjątku.

(Odziedziczone po Exception)
InnerException

Exception Pobiera wystąpienie, które spowodowało bieżący wyjątek.

(Odziedziczone po Exception)
Message

Pobiera komunikat opisujący bieżący wyjątek.

(Odziedziczone po Exception)
Source

Pobiera lub ustawia nazwę aplikacji lub obiektu, który powoduje błąd.

(Odziedziczone po Exception)
StackTrace

Pobiera reprezentację ciągu natychmiastowych ramek w stosie wywołań.

(Odziedziczone po Exception)
TargetSite

Pobiera metodę, która zgłasza bieżący wyjątek.

(Odziedziczone po Exception)

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetBaseException()

Po przesłonięciu w klasie pochodnej funkcja zwraca Exception główną przyczynę co najmniej jednego kolejnego wyjątku.

(Odziedziczone po Exception)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetObjectData(SerializationInfo, StreamingContext)

Po zastąpieniu w klasie pochodnej ustawia SerializationInfo element z informacjami o wyjątku.

(Odziedziczone po Exception)
GetType()

Pobiera typ środowiska uruchomieniowego bieżącego wystąpienia.

(Odziedziczone po Exception)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Tworzy i zwraca reprezentację ciągu bieżącego wyjątku.

(Odziedziczone po Exception)

Zdarzenia

SerializeObjectState
Nieaktualne.

Występuje, gdy wyjątek jest serializowany w celu utworzenia obiektu stanu wyjątku zawierającego serializowane dane o wyjątku.

(Odziedziczone po Exception)

Dotyczy

Zobacz też