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 잘못된 인덱스가 배열 또는 컬렉션의 멤버에 액세스하거나 버퍼의 특정 위치에서 읽거나 쓰는 데 사용되는 경우 예외가 throw됩니다. 이 예외는 클래스에서 상속되지만 고유한 멤버는 Exception 추가하지 않습니다.

일반적으로 IndexOutOfRangeException 개발자 오류로 인해 예외가 throw됩니다. 예외를 처리하는 대신 오류의 원인을 진단하고 코드를 수정해야 합니다. 오류의 가장 일반적인 원인은 다음과 같습니다.

  • 다음 예제와 같이 컬렉션 또는 0부터 시작하는 배열의 상한이 멤버 또는 요소 수보다 1보다 작다는 점을 잊어버리세요.

    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'
    

    또는 배열의 모든 요소를 인덱스로 반복하는 대신 문(C#), 문(F#) for...in 또는 For Each 문(Visual Basic)을 사용할 foreach 수 있습니다.

  • 적절하게 차원화되지 않았고 원래 배열보다 적은 요소가 있는 다른 배열에 배열 요소를 할당하려고 시도합니다. 다음 예제에서는 배열의 마지막 요소를 배열의 value1 동일한 요소에 value2 할당하려고 시도합니다. 그러나 배열의 value2 크기가 7개 요소가 아닌 6개로 잘못 차원되었습니다. 결과적으로 할당은 예외를 IndexOutOfRangeException throw합니다.

    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()
    
  • 검색 메서드에서 반환된 값을 사용하여 특정 인덱스 위치에서 시작하는 배열 또는 컬렉션의 일부를 반복합니다. 검색 작업에서 일치하는 항목을 찾았는지 여부를 확인하는 것을 잊어버린 경우 런타임은 이 예제와 같이 예외를 throw합니다 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 throw됩니다.

    • 시작 인덱스가 반복하려는 배열의 차원보다 크거나 같 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  
      

      배열 또는 컬렉션의 시작 인덱스가 음수가 될 수 없습니다.

  • 배열이 0부터 시작해야 한다고 가정합니다. 0부터 시작하지 않는 배열은 메서드에서 Array.CreateInstance(Type, Int32[], Int32[]) 만들 수 있으며 CLS 규격은 아니지만 COM interop에서 반환할 수 있습니다. 다음 예제에서는 메서드에서 IndexOutOfRangeException 만든 0이 아닌 배열을 반복하려고 할 때 throw되는 배열을 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#), 문(F#) for...in 또는 문(Visual Basic)을 For Each 사용할 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 개체에서 읽기, 여러 스레드에서 동일한 StreamWriter 개체에 쓰기 또는 다른 스레드에서 개체 Hashtable 열거와 같은 작업은 개체가 스레드로부터 안전한 방식으로 액세스되지 않는 경우 throw IndexOutOfRangeException 할 수 있습니다. 이 예외는 일반적으로 경합 조건에 의존하기 때문에 간헐적으로 발생합니다.

하드 코딩된 인덱스 값을 사용하여 배열을 조작하면 인덱스 값이 올바르지 않거나 유효하지 않거나 조작되는 배열의 크기가 예기치 않은 경우 예외가 발생할 수 있습니다. 작업에서 예외가 IndexOutOfRangeException throw되지 않도록 하려면 다음을 수행할 수 있습니다.

  • foreach 문(C#)을 사용하여 배열의 요소를 반복합니다. in 문(F#) 또는 For Each... 인덱스별로 요소를 반복하는 대신 다음 구문(Visual Basic)입니다.

  • 메서드에서 반환된 인덱스부터 시작하여 메서드에서 반환 Array.GetUpperBoundArray.GetLowerBound 인덱스로 끝나는 인덱스로 요소를 반복합니다.

  • 한 배열의 요소를 다른 배열에 할당하는 경우 대상 배열의 속성을 비교하여 Array.Length 원본 배열만큼 많은 요소가 있는지 확인합니다.

인스턴스의 초기 속성 값의 목록을 IndexOutOfRangeException, 참조는 IndexOutOfRangeException 생성자입니다.

다음 IL(중간 언어) 지침은 다음을 throw IndexOutOfRangeException합니다.

  • ldelem.<type>

  • ldelema

  • stelem.<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

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 예외에 대한 문자열 표현을 만들고 반환합니다.

(다음에서 상속됨 Exception)

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

적용 대상

추가 정보