IndexOutOfRangeException Osztály

Definíció

Az a kivétel, amely akkor fordul elő, ha egy tömb vagy gyűjtemény egy olyan elemét próbálják elérni, amelynek indexe kívül esik a határán.

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
Öröklődés
IndexOutOfRangeException
Öröklődés
IndexOutOfRangeException
Attribútumok

Megjegyzések

Kivétel IndexOutOfRangeException akkor fordul elő, ha egy tömb vagy gyűjtemény egy tagjának elérésére, illetve egy puffer egy adott helyről való olvasására vagy írására használ érvénytelen indexet. Ez a kivétel az Exception osztálytól öröklődik, de nem ad hozzá egyedi tagokat.

A rendszer általában IndexOutOfRangeException fejlesztői hiba miatt kivételt okoz. A kivétel kezelése helyett diagnosztizálnia kell a hiba okát, és ki kell javítania a kódot. A hiba leggyakoribb okai a következők:

  • Elfelejtve, hogy egy gyűjtemény vagy egy nulla alapú tömb felső határa eggyel kevesebb, mint a tagok vagy elemek száma, ahogy az alábbi példa szemlélteti.

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

    A hiba kijavításához használhatja a következőhöz hasonló kódot.

    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'
    

    A tömb összes elemének index szerinti iterálása helyett használhatja a foreach utasítást (C#-ban), a for...in utasítást (F#-ban), vagy a For Each utasítást (Visual Basic).

  • Olyan tömbelem hozzárendelése egy másik tömbhöz, amely nem lett megfelelően méretezve, és kevesebb elemből áll, mint az eredeti tömb. Az alábbi példa a tömb utolsó elemét value1 a tömb ugyanazon eleméhez value2 próbálja hozzárendelni. A tömb azonban helytelenül lett méretezve, value2 hogy hét elem helyett hat legyen. Ennek eredményeképpen a hozzárendelés kivételt IndexOutOfRangeException okoz.

    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()
    
  • Egy keresési módszer által visszaadott érték használatával egy tömb vagy gyűjtemény egy részét iterálja egy adott indexpozíciótól kezdve. Ha elfelejtette ellenőrizni, hogy a keresési művelet talált-e egyezést, a futtatókörnyezet kivételt IndexOutOfRangeException jelez, ahogyan az ebben a példában látható.

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

    Ebben az esetben a metódus - List<T>.IndexOf 1 értéket ad vissza, amely érvénytelen indexérték, ha nem talál egyezést. A hiba kijavításához ellenőrizze a keresési módszer visszatérési értékét a tömb iterálása előtt, ahogyan az ebben a példában látható.

    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.
    
  • Egy lekérdezés által visszaadott eredményhalmaz, gyűjtemény vagy tömb használata vagy számbavétele anélkül, hogy tesztelni szeretné, hogy a visszaadott objektum rendelkezik-e érvényes adatokkal.

  • Számított érték használatával határozza meg a kezdő indexet, a záró indexet vagy az iterálandó elemek számát. Ha a számítás eredménye váratlan, az kivételt IndexOutOfRangeException eredményezhet. A tömb vagy gyűjtemény iterálása előtt ellenőriznie kell a program logikáját az indexérték kiszámításában, és ellenőriznie kell az értéket. A következő feltételeknek mind igaznak kell lenniük; ellenkező esetben kivétel történik IndexOutOfRangeException :

    • A kezdő indexnek nagyobbnak vagy egyenlőnek Array.GetLowerBound kell lennie az iterálni kívánt tömb méreténél, vagy egy gyűjtemény esetében 0-nál nagyobbnak vagy egyenlőnek kell lennie.

    • A záró index nem haladhatja meg Array.GetUpperBound az iterálni kívánt tömb dimenzióját, vagy nem lehet nagyobb, mint egy Count gyűjtemény tulajdonsága.

    • Az alábbi egyenletnek igaznak kell lennie az iterálni kívánt tömb dimenziójára:

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

      Gyűjtemény esetén a következő egyenletnek igaznak kell lennie:

      start_index >= 0 And start_index + items_to_iterate <= Count
      

      Tip

      Egy tömb vagy gyűjtemény kezdő indexe soha nem lehet negatív szám.

  • Feltételezve, hogy egy tömbnek nulla alapúnak kell lennie. A nem nulla alapú tömbök a Array.CreateInstance(Type, Int32[], Int32[]) módszerrel hozhatók létre, és a COM interop által visszaadhatók, bár nem CLS-kompatibilisek. Az alábbi példa azt IndexOutOfRangeException szemlélteti, hogy a metódus által Array.CreateInstance(Type, Int32[], Int32[]) létrehozott nem nulla alapú tömb iterációjakor milyen műveletet hajt végre.

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

    A hiba kijavításához az alábbi példához hasonlóan meghívhatja a GetLowerBound metódust a tömb kezdő indexével kapcsolatos feltételezések helyett.

    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
    

    Vegye figyelembe, hogy amikor meghívja a GetLowerBound metódust egy tömb kezdő indexének lekéréséhez, a metódust is meg kell hívnia a Array.GetUpperBound(Int32) záró index lekéréséhez.

  • Az index és az adott index értékének összekeverése numerikus tömbben vagy gyűjteményben. Ez a probléma általában a foreach utasítás (C#-ban), a for...in utasítás (F#-ban) vagy a For Each utasítás (Visual Basic) használatakor fordul elő. Az alábbi példa a problémát szemlélteti.

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

    Az iterációs szerkezet egy tömb vagy gyűjtemény minden értékét visszaadja, nem pedig az indexét. A kivétel megszüntetéséhez használja ezt a kódot.

    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
    
  • Érvénytelen oszlopnév megadása a DataView.Sort tulajdonságnak.

  • Megsérti a szál biztonságát. Az olyan műveletek, mint az azonos StreamReader objektumból való olvasás, több szálból ugyanarra StreamWriter az objektumra való írás, vagy az objektumok számbavétele egy Hashtable másik szálból, olyan műveleteket okozhatnak IndexOutOfRangeException , ha az objektum nem érhető el szálbiztos módon. Ez a kivétel általában időszakos, mert egy versenyfeltételre támaszkodik.

Ha a tömbök manipulálására keményen kódolt indexértékeket használ, az valószínűleg kivételt jelent, ha az index értéke helytelen vagy érvénytelen, vagy ha a módosítandó tömb mérete váratlan. Ha meg szeretné akadályozni, hogy egy művelet kivételt IndexOutOfRangeException tegyen, tegye a következőket:

  • Iterálja a tömb elemeit a foreach utasítással (C#-ban), a for... in utasítás (F#-ban) vagy a Az egyes... Következő szerkezet (Visual Basic) az elemek index szerinti iterálása helyett.

  • Az elemeket index szerint iterálja a metódus által visszaadott indextől kezdve a metódus által Array.GetLowerBoundArray.GetUpperBound visszaadott indexig.

  • Ha az egyik tömb elemeit egy másikhoz rendeli, a tulajdonságok összehasonlításával Array.Length győződjön meg arról, hogy a céltömb legalább annyi elemmel rendelkezik, mint a forrástömb.

A IndexOutOfRangeException példány kezdeti tulajdonságainak listájáért tekintse meg a IndexOutOfRangeException konstruktorokat.

A következő középfokú nyelvre (IL) vonatkozó utasítások a következők IndexOutOfRangeException:

  • ldelem.<Típus>

  • ldelema

  • stelem.<Típus>

IndexOutOfRangeException A HRESULT COR_E_INDEXOUTOFRANGE használja, amelynek értéke 0x80131508.

Konstruktorok

Name Description
IndexOutOfRangeException()

Inicializálja a IndexOutOfRangeException osztály új példányát.

IndexOutOfRangeException(String, Exception)

Inicializálja az IndexOutOfRangeException osztály új példányát egy megadott hibaüzenettel és a kivétel okaként szolgáló belső kivételre mutató hivatkozással.

IndexOutOfRangeException(String)

Inicializálja az IndexOutOfRangeException osztály új példányát egy megadott hibaüzenettel.

Tulajdonságok

Name Description
Data

Lekéri a kulcs-/érték párok gyűjteményét, amelyek további, felhasználó által definiált információkat biztosítanak a kivételről.

(Öröklődés forrása Exception)
HelpLink

Lekéri vagy beállítja a kivételhez társított súgófájlra mutató hivatkozást.

(Öröklődés forrása Exception)
HResult

Lekéri vagy beállítja a HRESULT-ot, egy kódolt numerikus értéket, amely egy adott kivételhez van hozzárendelve.

(Öröklődés forrása Exception)
InnerException

Lekéri az Exception aktuális kivételt okozó példányt.

(Öröklődés forrása Exception)
Message

Az aktuális kivételt leíró üzenet jelenik meg.

(Öröklődés forrása Exception)
Source

Lekéri vagy beállítja az alkalmazás vagy a hibát okozó objektum nevét.

(Öröklődés forrása Exception)
StackTrace

Lekéri a hívásverem közvetlen kereteinek sztringképét.

(Öröklődés forrása Exception)
TargetSite

Lekéri az aktuális kivételt okozó metódust.

(Öröklődés forrása Exception)

Metódusok

Name Description
Equals(Object)

Meghatározza, hogy a megadott objektum egyenlő-e az aktuális objektummal.

(Öröklődés forrása Object)
GetBaseException()

Ha egy származtatott osztály felül van bírálva, egy Exception vagy több későbbi kivétel kiváltó okát adja vissza.

(Öröklődés forrása Exception)
GetHashCode()

Ez az alapértelmezett kivonatoló függvény.

(Öröklődés forrása Object)
GetObjectData(SerializationInfo, StreamingContext)
Elavult.

Ha felül van bírálva egy származtatott osztályban, a SerializationInfo kivétel adatait adja meg.

(Öröklődés forrása Exception)
GetType()

Lekéri az aktuális példány futtatókörnyezeti típusát.

(Öröklődés forrása Exception)
MemberwiseClone()

Az aktuális Objectpéldány sekély másolatát hozza létre.

(Öröklődés forrása Object)
ToString()

Létrehozza és visszaadja az aktuális kivétel sztring-ábrázolását.

(Öröklődés forrása Exception)

esemény

Name Description
SerializeObjectState
Elavult.

Akkor fordul elő, ha a kivétel szerializálva van egy kivételállapot-objektum létrehozásához, amely szerializált adatokat tartalmaz a kivételről.

(Öröklődés forrása Exception)

A következőre érvényes:

Lásd még