System.InvalidOperationException 클래스

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

InvalidOperationException 은 잘못된 인수 이외의 이유로 인해 메서드를 호출하지 못한 경우에 사용됩니다. 일반적으로 개체의 상태가 메서드 호출을 지원할 수 없을 때 throw됩니다. 예를 들어 예외 InvalidOperationException 는 다음과 같은 메서드에 의해 throw됩니다.

  • IEnumerator.MoveNext 열거자를 만든 후 컬렉션의 개체가 수정되면 입니다. 자세한 내용은 컬렉션을 반복하는 동안 변경 내용을 참조 하세요.
  • ResourceSet.GetString 메서드를 호출하기 전에 리소스 집합이 닫혀 있으면 입니다.
  • XContainer.Add추가할 개체 또는 개체가 잘못 구조화된 XML 문서를 생성하면 입니다.
  • 기본 또는 UI 스레드가 아닌 스레드에서 UI를 조작하려고 시도하는 메서드입니다.

Important

예외는 InvalidOperationException 다양한 상황에서 throw될 수 있으므로 속성에서 반환 Message 된 예외 메시지를 읽는 것이 중요합니다.

InvalidOperationException 는 값이 0x80131509 HRESULT COR_E_INVALIDOPERATION를 사용합니다.

인스턴스 InvalidOperationException의 초기 속성 값 목록은 생성자를 참조 InvalidOperationException 하세요.

InvalidOperationException 예외의 일반적인 원인

다음 섹션에서는 앱에서 InvalidOperationException 예외가 throw되는 몇 가지 일반적인 사례를 보여 줍니다. 문제를 처리하는 방법은 특정 상황에 따라 달라집니다. 그러나 가장 일반적으로 예외는 개발자 오류로 인해 발생하며 예외를 InvalidOperationException 예상 및 방지할 수 있습니다.

비 UI 스레드에서 UI 스레드 업데이트

종종 작업자 스레드 애플리케이션의 사용자 인터페이스에 표시 되는 데이터 수집을 포함 하는 몇 가지 백그라운드 작업 하는 데 사용 됩니다. 하지만. Windows Forms 및 WPF(Windows Presentation Foundation)와 같은 .NET용 대부분의 GUI(그래픽 사용자 인터페이스) 애플리케이션 프레임워크를 사용하면 UI(기본 또는 UI 스레드)를 만들고 관리하는 스레드에서만 GUI 개체에 액세스할 수 있습니다. InvalidOperationException UI 스레드가 아닌 스레드에서 UI 요소에 액세스하려고 하면 throw됩니다. 예외 메시지의 텍스트는 다음 표에 나와 있습니다.

응용 프로그램 유형 메시지
WPF 앱 호출 스레드는 다른 스레드가 소유하므로 이 개체에 액세스할 수 없습니다.
UWP 앱 애플리케이션은 다른 스레드에 대해 마샬링된 인터페이스를 호출했습니다.
Windows Forms 앱 스레드 간 작업이 유효하지 않음: 만든 스레드가 아닌 다른 스레드에서 액세스한 'TextBox1' 컨트롤입니다.

.NET용 UI 프레임워크는 UI 요소의 멤버에 대한 호출이 UI 스레드에서 실행되는지 여부와 UI 스레드에서 호출을 예약하는 다른 메서드를 검사 메서드를 포함하는 디스패처 패턴을 구현합니다.

  • WPF 앱에서 메서드를 호출하여 메서드가 Dispatcher.CheckAccess 비 UI 스레드에서 실행되고 있는지 확인합니다. 메서드가 UI 스레드 false 에서 실행 중이고 그렇지 않으면 반환 true 됩니다. 메서드의 오버로드 Dispatcher.Invoke 중 하나를 호출하여 UI 스레드에서 호출을 예약합니다.
  • UWP 앱에서 속성을 검사 CoreDispatcher.HasThreadAccess 메서드가 비 UI 스레드에서 실행 중인지 확인합니다. 메서드를 CoreDispatcher.RunAsync 호출하여 UI 스레드를 업데이트하는 대리자를 실행합니다.
  • Windows Forms 앱에서 이 속성을 사용하여 메서드가 Control.InvokeRequired UI가 아닌 스레드에서 실행 중인지 확인합니다. 메서드의 오버로드 Control.Invoke 중 하나를 호출하여 UI 스레드를 업데이트하는 대리자를 실행합니다.

다음 예제에서는 UI 요소를 만든 스레드 이외의 스레드에서 업데이트하려고 할 때 throw되는 예외를 보여 InvalidOperationException 줍니다. 각 예제에서는 두 개의 컨트롤을 만들어야 합니다.

  • 라는 textBox1텍스트 상자 컨트롤입니다. Windows Forms 앱에서는 해당 Multiline 속성을 true.로 설정해야 합니다.
  • 라는 threadExampleBtn단추 컨트롤입니다. 이 예제에서는 단추 Click 이벤트에 대한 처리기를 ThreadsExampleBtn_Click제공합니다.

각 경우에 threadExampleBtn_Click 이벤트 처리기는 메서드를 두 번 호출합니다 DoSomeWork . 첫 번째 호출은 동기적으로 실행되고 성공합니다. 그러나 두 번째 호출은 스레드 풀 스레드에서 비동기적으로 실행되므로 UI가 아닌 스레드에서 UI를 업데이트하려고 시도합니다. 이로 인해 예외가 발생합니다 InvalidOperationException .

WPF 앱

private async void threadExampleBtn_Click(object sender, RoutedEventArgs e)
{
    textBox1.Text = String.Empty;

    textBox1.Text = "Simulating work on UI thread.\n";
    DoSomeWork(20);
    textBox1.Text += "Work completed...\n";

    textBox1.Text += "Simulating work on non-UI thread.\n";
    await Task.Run(() => DoSomeWork(1000));
    textBox1.Text += "Work completed...\n";
}

private async void DoSomeWork(int milliseconds)
{
    // Simulate work.
    await Task.Delay(milliseconds);

    // Report completion.
    var msg = String.Format("Some work completed in {0} ms.\n", milliseconds);
    textBox1.Text += msg;
}

다음 버전의 메서드는 DoSomeWork WPF 앱에서 예외를 제거합니다.

private async void DoSomeWork(int milliseconds)
{
    // Simulate work.
    await Task.Delay(milliseconds);

    // Report completion.
    bool uiAccess = textBox1.Dispatcher.CheckAccess();
    String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
                               milliseconds, uiAccess ? String.Empty : "non-");
    if (uiAccess)
        textBox1.Text += msg;
    else
        textBox1.Dispatcher.Invoke(() => { textBox1.Text += msg; });
}

Windows Forms 앱

List<String> lines = new List<String>();

private async void threadExampleBtn_Click(object sender, EventArgs e)
{
    textBox1.Text = String.Empty;
    lines.Clear();

    lines.Add("Simulating work on UI thread.");
    textBox1.Lines = lines.ToArray();
    DoSomeWork(20);

    lines.Add("Simulating work on non-UI thread.");
    textBox1.Lines = lines.ToArray();
    await Task.Run(() => DoSomeWork(1000));

    lines.Add("ThreadsExampleBtn_Click completes. ");
    textBox1.Lines = lines.ToArray();
}

private async void DoSomeWork(int milliseconds)
{
    // simulate work
    await Task.Delay(milliseconds);

    // report completion
    lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds));
    textBox1.Lines = lines.ToArray();
}
Dim lines As New List(Of String)()
Private Async Sub threadExampleBtn_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox1.Text = String.Empty
    lines.Clear()

    lines.Add("Simulating work on UI thread.")
    TextBox1.Lines = lines.ToArray()
    DoSomeWork(20)

    lines.Add("Simulating work on non-UI thread.")
    TextBox1.Lines = lines.ToArray()
    Await Task.Run(Sub() DoSomeWork(1000))

    lines.Add("ThreadsExampleBtn_Click completes. ")
    TextBox1.Lines = lines.ToArray()
End Sub

Private Async Sub DoSomeWork(milliseconds As Integer)
    ' Simulate work.
    Await Task.Delay(milliseconds)

    ' Report completion.
    lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds))
    textBox1.Lines = lines.ToArray()
End Sub

다음 버전의 메서드는 DoSomeWork Windows Forms 앱에서 예외를 제거합니다.

private async void DoSomeWork(int milliseconds)
{
    // simulate work
    await Task.Delay(milliseconds);

    // Report completion.
    bool uiMarshal = textBox1.InvokeRequired;
    String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
                               milliseconds, uiMarshal ? String.Empty : "non-");
    lines.Add(msg);

    if (uiMarshal) {
        textBox1.Invoke(new Action(() => { textBox1.Lines = lines.ToArray(); }));
    }
    else {
        textBox1.Lines = lines.ToArray();
    }
}
Private Async Sub DoSomeWork(milliseconds As Integer)
    ' Simulate work.
    Await Task.Delay(milliseconds)

    ' Report completion.
    Dim uiMarshal As Boolean = TextBox1.InvokeRequired
    Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
                                      milliseconds, If(uiMarshal, String.Empty, "non-"))
    lines.Add(msg)

    If uiMarshal Then
        TextBox1.Invoke(New Action(Sub() TextBox1.Lines = lines.ToArray()))
    Else
        TextBox1.Lines = lines.ToArray()
    End If
End Sub

반복하는 동안 컬렉션 변경

foreach C#, for...in F#의 문 또는 For Each Visual Basic의 문은 컬렉션의 멤버를 반복하고 개별 요소를 읽거나 수정하는 데 사용됩니다. 그러나 컬렉션에서 항목을 추가하거나 제거하는 데는 사용할 수 없습니다. 이렇게 InvalidOperationException 하면 "컬렉션이 수정되었습니다. 열거형 작업은 실행되지 않을 수 있습니다."

다음 예제에서는 컬렉션에 각 정수의 제곱을 추가하려고 시도하는 정수 컬렉션을 반복합니다. 이 예제에서는 메서드에 InvalidOperationException 대한 첫 번째 호출을 throw합니다 List<T>.Add .

using System;
using System.Collections.Generic;

public class IteratingEx1
{
    public static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 5 };
        foreach (var number in numbers)
        {
            int square = (int)Math.Pow(number, 2);
            Console.WriteLine("{0}^{1}", number, square);
            Console.WriteLine("Adding {0} to the collection...\n", square);
            numbers.Add(square);
        }
    }
}
// The example displays the following output:
//    1^1
//    Adding 1 to the collection...
//
//
//    Unhandled Exception: System.InvalidOperationException: Collection was modified;
//       enumeration operation may not execute.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
//       at Example.Main()
open System

let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
for number in numbers do
    let square = Math.Pow(number, 2) |> int
    printfn $"{number}^{square}"
    printfn $"Adding {square} to the collection...\n"
    numbers.Add square

// The example displays the following output:
//    1^1
//    Adding 1 to the collection...
//
//
//    Unhandled Exception: System.InvalidOperationException: Collection was modified
//       enumeration operation may not execute.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
//       at <StartupCode$fs>.main()
Imports System.Collections.Generic

Module Example6
    Public Sub Main()
        Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
        For Each number In numbers
            Dim square As Integer = CInt(Math.Pow(number, 2))
            Console.WriteLine("{0}^{1}", number, square)
            Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
                           square)
            numbers.Add(square)
        Next
    End Sub
End Module
' The example displays the following output:
'    1^1
'    Adding 1 to the collection...
'    
'    
'    Unhandled Exception: System.InvalidOperationException: Collection was modified; 
'       enumeration operation may not execute.
'       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
'       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
'       at Example.Main()

애플리케이션 논리에 따라 두 가지 방법 중 하나에서 예외를 제거할 수 있습니다.

  • 반복하는 동안 요소를 컬렉션에 추가해야 하는 경우 , 또는 대신 (for..toF#) 문을 foreachfor...in사용하여 for 인덱스로 반복할 수 For Each있습니다. 다음 예제에서는 for 문을 사용하여 컬렉션의 숫자 제곱을 컬렉션에 추가합니다.

    using System;
    using System.Collections.Generic;
    
    public class IteratingEx2
    {
        public static void Main()
        {
            var numbers = new List<int>() { 1, 2, 3, 4, 5 };
    
            int upperBound = numbers.Count - 1;
            for (int ctr = 0; ctr <= upperBound; ctr++)
            {
                int square = (int)Math.Pow(numbers[ctr], 2);
                Console.WriteLine("{0}^{1}", numbers[ctr], square);
                Console.WriteLine("Adding {0} to the collection...\n", square);
                numbers.Add(square);
            }
    
            Console.WriteLine("Elements now in the collection: ");
            foreach (var number in numbers)
                Console.Write("{0}    ", number);
        }
    }
    // The example displays the following output:
    //    1^1
    //    Adding 1 to the collection...
    //
    //    2^4
    //    Adding 4 to the collection...
    //
    //    3^9
    //    Adding 9 to the collection...
    //
    //    4^16
    //    Adding 16 to the collection...
    //
    //    5^25
    //    Adding 25 to the collection...
    //
    //    Elements now in the collection:
    //    1    2    3    4    5    1    4    9    16    25
    
    open System
    open System.Collections.Generic
    
    let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
    
    let upperBound = numbers.Count - 1
    for i = 0 to upperBound do
        let square = Math.Pow(numbers[i], 2) |> int
        printfn $"{numbers[i]}^{square}"
        printfn $"Adding {square} to the collection...\n"
        numbers.Add square
    
    printfn "Elements now in the collection: "
    for number in numbers do
        printf $"{number}    "
    // The example displays the following output:
    //    1^1
    //    Adding 1 to the collection...
    //
    //    2^4
    //    Adding 4 to the collection...
    //
    //    3^9
    //    Adding 9 to the collection...
    //
    //    4^16
    //    Adding 16 to the collection...
    //
    //    5^25
    //    Adding 25 to the collection...
    //
    //    Elements now in the collection:
    //    1    2    3    4    5    1    4    9    16    25
    
    Imports System.Collections.Generic
    
    Module Example7
        Public Sub Main()
            Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
            Dim upperBound = numbers.Count - 1
    
            For ctr As Integer = 0 To upperBound
                Dim square As Integer = CInt(Math.Pow(numbers(ctr), 2))
                Console.WriteLine("{0}^{1}", numbers(ctr), square)
                Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
                               square)
                numbers.Add(square)
            Next
    
            Console.WriteLine("Elements now in the collection: ")
            For Each number In numbers
                Console.Write("{0}    ", number)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '    1^1
    '    Adding 1 to the collection...
    '    
    '    2^4
    '    Adding 4 to the collection...
    '    
    '    3^9
    '    Adding 9 to the collection...
    '    
    '    4^16
    '    Adding 16 to the collection...
    '    
    '    5^25
    '    Adding 25 to the collection...
    '    
    '    Elements now in the collection:
    '    1    2    3    4    5    1    4    9    16    25
    

    루프 내에서 루프를 적절하게 종료하는 카운터를 사용하거나, 뒤로, 1에서 Count 0으로 반복하거나, 예제와 같이 배열의 요소 수를 변수에 할당하고 이를 사용하여 루프의 상한을 설정하여 컬렉션을 반복하기 전에 반복 횟수를 설정해야 합니다. 그렇지 않으면 모든 반복에서 요소가 컬렉션에 추가되면 무한 루프가 발생합니다.

  • 반복하는 동안 컬렉션에 요소를 추가할 필요가 없는 경우 컬렉션을 반복할 때 추가할 임시 컬렉션에 추가할 요소를 저장할 수 있습니다. 다음 예제에서는 이 방법을 사용하여 컬렉션의 숫자 제곱을 임시 컬렉션에 추가한 다음 컬렉션을 단일 배열 개체로 결합합니다.

    using System;
    using System.Collections.Generic;
    
    public class IteratingEx3
    {
        public static void Main()
        {
            var numbers = new List<int>() { 1, 2, 3, 4, 5 };
            var temp = new List<int>();
    
            // Square each number and store it in a temporary collection.
            foreach (var number in numbers)
            {
                int square = (int)Math.Pow(number, 2);
                temp.Add(square);
            }
    
            // Combine the numbers into a single array.
            int[] combined = new int[numbers.Count + temp.Count];
            Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count);
            Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count);
    
            // Iterate the array.
            foreach (var value in combined)
                Console.Write("{0}    ", value);
        }
    }
    // The example displays the following output:
    //       1    2    3    4    5    1    4    9    16    25
    
    open System
    open System.Collections.Generic
    
    let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
    let temp = ResizeArray()
    
    // Square each number and store it in a temporary collection.
    for number in numbers do
        let square = Math.Pow(number, 2) |> int
        temp.Add square
    
    // Combine the numbers into a single array.
    let combined = Array.zeroCreate<int> (numbers.Count + temp.Count)
    Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count)
    Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count)
    
    // Iterate the array.
    for value in combined do
        printf $"{value}    "
    // The example displays the following output:
    //       1    2    3    4    5    1    4    9    16    25
    
    Imports System.Collections.Generic
    
    Module Example8
        Public Sub Main()
            Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
            Dim temp As New List(Of Integer)()
    
            ' Square each number and store it in a temporary collection.
            For Each number In numbers
                Dim square As Integer = CInt(Math.Pow(number, 2))
                temp.Add(square)
            Next
    
            ' Combine the numbers into a single array.
            Dim combined(numbers.Count + temp.Count - 1) As Integer
            Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count)
            Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count)
    
            ' Iterate the array.
            For Each value In combined
                Console.Write("{0}    ", value)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       1    2    3    4    5    1    4    9    16    25
    

개체를 비교할 수 없는 배열 또는 컬렉션 정렬

메서드 또는 List<T>.Sort() 메서드와 같은 Array.Sort(Array) 범용 정렬 메서드는 일반적으로 정렬할 개체 중 하나 이상이 또는 IComparable 인터페이스를 IComparable<T> 구현해야 합니다. 그렇지 않은 경우 컬렉션 또는 배열을 정렬할 수 없으며 메서드는 예외를 InvalidOperationException throw합니다. 다음 예제에서는 클래스를 Person 정의하고, 제네릭 List<T> 개체에 두 개체 Person 를 저장하고, 정렬을 시도합니다. 예제의 출력에서와 같이 메서드에 대한 호출은 List<T>.Sort() .를 InvalidOperationExceptionthrow합니다.

using System;
using System.Collections.Generic;

public class Person1
{
    public Person1(string fName, string lName)
    {
        FirstName = fName;
        LastName = lName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ListSortEx1
{
    public static void Main()
    {
        var people = new List<Person1>();

        people.Add(new Person1("John", "Doe"));
        people.Add(new Person1("Jane", "Doe"));
        people.Sort();
        foreach (var person in people)
            Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
//       System.ArgumentException: At least one object must implement IComparable.
//       at System.Collections.Comparer.Compare(Object a, Object b)
//       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
//       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       --- End of inner exception stack trace ---
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
//       at Example.Main()
type Person(firstName: string, lastName: string) =
    member val FirstName = firstName with get, set
    member val LastName = lastName with get, set

let people = ResizeArray()

people.Add(Person("John", "Doe"))
people.Add(Person("Jane", "Doe"))
people.Sort()
for person in people do
    printfn $"{person.FirstName} {person.LastName}"
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
//       System.ArgumentException: At least one object must implement IComparable.
//       at System.Collections.Comparer.Compare(Object a, Object b)
//       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
//       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       --- End of inner exception stack trace ---
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
//       at <StartupCode$fs>.main()
Imports System.Collections.Generic

Public Class Person9
    Public Sub New(fName As String, lName As String)
        FirstName = fName
        LastName = lName
    End Sub

    Public Property FirstName As String
    Public Property LastName As String
End Class

Module Example9
    Public Sub Main()
        Dim people As New List(Of Person9)()

        people.Add(New Person9("John", "Doe"))
        people.Add(New Person9("Jane", "Doe"))
        people.Sort()
        For Each person In people
            Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
        Next
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> 
'       System.ArgumentException: At least one object must implement IComparable.
'       at System.Collections.Comparer.Compare(Object a, Object b)
'       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
'       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
'       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
'       --- End of inner exception stack trace ---
'       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
'       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
'       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
'       at Example.Main()

다음 세 가지 방법 중에서 예외를 제거할 수 있습니다.

  • 정렬하려는 형식을 소유할 수 있는 경우(즉, 소스 코드를 제어하는 경우) 수정하여 인터페이스를 IComparable 구현 IComparable<T> 할 수 있습니다. 이렇게 하려면 메서드 또는 CompareTo 메서드를 IComparable<T>.CompareTo 구현해야 합니다. 기존 형식에 인터페이스 구현을 추가하는 것은 호환성이 손상되는 변경이 아닙니다.

    다음 예제에서는 이 방법을 사용하여 클래스에 대한 구현을 IComparable<T>Person 제공합니다. 컬렉션 또는 배열의 일반 정렬 메서드를 계속 호출할 수 있으며 예제의 출력에서 볼 수 있듯이 컬렉션이 성공적으로 정렬됩니다.

    using System;
    using System.Collections.Generic;
    
    public class Person2 : IComparable<Person>
    {
        public Person2(String fName, String lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    
        public String FirstName { get; set; }
        public String LastName { get; set; }
    
        public int CompareTo(Person other)
        {
            return String.Format("{0} {1}", LastName, FirstName).
                   CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName));
        }
    }
    
    public class ListSortEx2
    {
        public static void Main()
        {
            var people = new List<Person2>();
    
            people.Add(new Person2("John", "Doe"));
            people.Add(new Person2("Jane", "Doe"));
            people.Sort();
            foreach (var person in people)
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
        }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    
    type Person(firstName: string, lastName: string) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
        
        interface IComparable<Person> with
            member this.CompareTo(other) =
                compare $"{this.LastName} {this.FirstName}" $"{other.LastName} {other.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(new Person("John", "Doe"))
    people.Add(new Person("Jane", "Doe"))
    people.Sort()
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person : Implements IComparable(Of Person)
       Public Sub New(fName As String, lName As String)
          FirstName = fName
          LastName = lName
       End Sub
       
       Public Property FirstName As String
       Public Property LastName As String
       
       Public Function CompareTo(other As Person) As Integer _
              Implements IComparable(Of Person).CompareTo
          Return String.Format("{0} {1}", LastName, FirstName).
                CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName))    
       End Function
    End Class
    
    Module Example10
        Public Sub Main()
            Dim people As New List(Of Person)()
    
            people.Add(New Person("John", "Doe"))
            people.Add(New Person("Jane", "Doe"))
            people.Sort()
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    
  • 정렬하려는 형식의 소스 코드를 수정할 수 없는 경우 인터페이스를 구현 IComparer<T> 하는 특수 용도의 정렬 클래스를 정의할 수 있습니다. 매개 변수를 포함하는 메서드의 오버로드를 Sort 호출할 IComparer<T> 수 있습니다. 이 방법은 여러 조건에 따라 개체를 정렬할 수 있는 특수 정렬 클래스를 개발하려는 경우에 특히 유용합니다.

    다음 예제에서는 컬렉션을 정렬 Person 하는 데 사용되는 사용자 지정 PersonComparer 클래스를 개발하여 이 방법을 사용합니다. 그런 다음 이 클래스의 인스턴스를 메서드에 List<T>.Sort(IComparer<T>) 전달합니다.

    using System;
    using System.Collections.Generic;
    
    public class Person3
    {
        public Person3(String fName, String lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }
    
    public class PersonComparer : IComparer<Person3>
    {
        public int Compare(Person3 x, Person3 y)
        {
            return String.Format("{0} {1}", x.LastName, x.FirstName).
                   CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName));
        }
    }
    
    public class ListSortEx3
    {
        public static void Main()
        {
            var people = new List<Person3>();
    
            people.Add(new Person3("John", "Doe"));
            people.Add(new Person3("Jane", "Doe"));
            people.Sort(new PersonComparer());
            foreach (var person in people)
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
        }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    open System.Collections.Generic
    
    type Person(firstName, lastName) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
    
    type PersonComparer() =
        interface IComparer<Person> with
            member _.Compare(x: Person, y: Person) =
                $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(Person("John", "Doe"))
    people.Add(Person("Jane", "Doe"))
    people.Sort(PersonComparer())
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person11
        Public Sub New(fName As String, lName As String)
            FirstName = fName
            LastName = lName
        End Sub
    
        Public Property FirstName As String
        Public Property LastName As String
    End Class
    
    Public Class PersonComparer : Implements IComparer(Of Person11)
        Public Function Compare(x As Person11, y As Person11) As Integer _
              Implements IComparer(Of Person11).Compare
            Return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName))
        End Function
    End Class
    
    Module Example11
        Public Sub Main()
            Dim people As New List(Of Person11)()
    
            people.Add(New Person11("John", "Doe"))
            people.Add(New Person11("Jane", "Doe"))
            people.Sort(New PersonComparer())
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    
  • 정렬하려는 형식의 소스 코드를 수정할 수 없는 경우 정렬을 수행하는 대리자를 만들 Comparison<T> 수 있습니다. 대리자 서명은

    Function Comparison(Of T)(x As T, y As T) As Integer
    
    int Comparison<T>(T x, T y)
    

    다음 예제에서는 대리자 서명과 일치하는 Comparison<T> 메서드를 PersonComparison 정의하여 이 방법을 사용합니다. 그런 다음 이 대리자를 메서드에 List<T>.Sort(Comparison<T>) 전달합니다.

    using System;
    using System.Collections.Generic;
    
    public class Person
    {
       public Person(String fName, String lName)
       {
          FirstName = fName;
          LastName = lName;
       }
    
       public String FirstName { get; set; }
       public String LastName { get; set; }
    }
    
    public class ListSortEx4
    {
       public static void Main()
       {
          var people = new List<Person>();
    
          people.Add(new Person("John", "Doe"));
          people.Add(new Person("Jane", "Doe"));
          people.Sort(PersonComparison);
          foreach (var person in people)
             Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
       }
    
       public static int PersonComparison(Person x, Person y)
       {
          return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName));
       }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    open System.Collections.Generic
    
    type Person(firstName, lastName) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
    
    let personComparison (x: Person) (y: Person) =
        $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(Person("John", "Doe"))
    people.Add(Person("Jane", "Doe"))
    people.Sort personComparison
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person12
        Public Sub New(fName As String, lName As String)
            FirstName = fName
            LastName = lName
        End Sub
    
        Public Property FirstName As String
        Public Property LastName As String
    End Class
    
    Module Example12
        Public Sub Main()
            Dim people As New List(Of Person12)()
    
            people.Add(New Person12("John", "Doe"))
            people.Add(New Person12("Jane", "Doe"))
            people.Sort(AddressOf PersonComparison)
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    
        Public Function PersonComparison(x As Person12, y As Person12) As Integer
            Return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName))
        End Function
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    

Null인 Null 허용<T> 를 기본 형식으로 캐스팅

기본 형식으로 값을 null 캐스팅 Nullable<T> 하려고 시도하면 예외가 throw InvalidOperationException 되고 오류 메시지가 표시됩니다. "Nullable 개체에는 값이 있어야 합니다.

다음 예제에서는 값이 InvalidOperationException 포함된 배열을 반복하려고 할 때 예외를 Nullable(Of Integer) throw합니다.

using System;
using System.Linq;

public class NullableEx1
{
   public static void Main()
   {
      var queryResult = new int?[] { 1, 2, null, 4 };
      var map = queryResult.Select(nullableInt => (int)nullableInt);

      // Display list.
      foreach (var num in map)
         Console.Write("{0} ", num);
      Console.WriteLine();
   }
}
// The example displays the following output:
//    1 2
//    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at Example.<Main>b__0(Nullable`1 nullableInt)
//       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
//       at Example.Main()
open System
open System.Linq

let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let map = queryResult.Select(fun nullableInt -> nullableInt.Value)

// Display list.
for num in map do
    printf $"{num} "
printfn ""
// The example displays the following output:
//    1 2
//    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at Example.<Main>b__0(Nullable`1 nullableInt)
//       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example13
    Public Sub Main()
        Dim queryResult = New Integer?() {1, 2, Nothing, 4}
        Dim map = queryResult.Select(Function(nullableInt) CInt(nullableInt))

        ' Display list.
        For Each num In map
            Console.Write("{0} ", num)
        Next
        Console.WriteLine()
    End Sub
End Module
' The example displays thIe following output:
'    1 2
'    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
'       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
'       at Example.<Main>b__0(Nullable`1 nullableInt)
'       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
'       at Example.Main()

예외를 방지하려면 다음을 수행합니다.

다음 예제에서는 예외를 방지하기 위해 둘 다 수행합니다 InvalidOperationException .

using System;
using System.Linq;

public class NullableEx2
{
   public static void Main()
   {
      var queryResult = new int?[] { 1, 2, null, 4 };
      var numbers = queryResult.Select(nullableInt => (int)nullableInt.GetValueOrDefault());

      // Display list using Nullable<int>.HasValue.
      foreach (var number in numbers)
         Console.Write("{0} ", number);
      Console.WriteLine();

      numbers = queryResult.Select(nullableInt => (int) (nullableInt.HasValue ? nullableInt : -1));
      // Display list using Nullable<int>.GetValueOrDefault.
      foreach (var number in numbers)
         Console.Write("{0} ", number);
      Console.WriteLine();
   }
}
// The example displays the following output:
//       1 2 0 4
//       1 2 -1 4
open System
open System.Linq

let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let numbers = queryResult.Select(fun nullableInt -> nullableInt.GetValueOrDefault())

// Display list using Nullable<int>.HasValue.
for number in numbers do
    printf $"{number} "
printfn ""

let numbers2 = queryResult.Select(fun nullableInt -> if nullableInt.HasValue then nullableInt.Value else -1)
// Display list using Nullable<int>.GetValueOrDefault.
for number in numbers2 do
    printf $"{number} "
printfn ""
// The example displays the following output:
//       1 2 0 4
//       1 2 -1 4
Imports System.Linq

Module Example14
    Public Sub Main()
        Dim queryResult = New Integer?() {1, 2, Nothing, 4}
        Dim numbers = queryResult.Select(Function(nullableInt) _
                                          CInt(nullableInt.GetValueOrDefault()))
        ' Display list.
        For Each number In numbers
            Console.Write("{0} ", number)
        Next
        Console.WriteLine()

        ' Use -1 to indicate a missing values.
        numbers = queryResult.Select(Function(nullableInt) _
                                      CInt(If(nullableInt.HasValue, nullableInt, -1)))
        ' Display list.
        For Each number In numbers
            Console.Write("{0} ", number)
        Next
        Console.WriteLine()

    End Sub
End Module
' The example displays the following output:
'       1 2 0 4
'       1 2 -1 4

빈 컬렉션에서 System.Linq.Enumerable 메서드 호출

,Enumerable.Average, Enumerable.First, Enumerable.Last, Enumerable.Max, Enumerable.MinEnumerable.SingleEnumerable.SingleOrDefault 메서드는 Enumerable.Aggregate시퀀스에 대한 작업을 수행하고 단일 결과를 반환합니다. 이러한 메서드의 일부 오버로드는 시퀀스가 비어 있을 때 예외를 throw InvalidOperationException 하고 다른 오버로드는 반환 null합니다. Enumerable.SingleOrDefault 또한 시퀀스에 InvalidOperationException 둘 이상의 요소가 포함된 경우 메서드는 예외를 throw합니다.

참고 항목

예외를 throw InvalidOperationException 하는 대부분의 메서드는 오버로드입니다. 선택한 오버로드의 동작을 이해해야 합니다.

다음 표에서는 일부 System.Linq.Enumerable 메서드를 호출하여 throw된 예외 개체의 InvalidOperationException 예외 메시지를 나열합니다.

메서드 메시지
Aggregate
Average
Last
Max
Min
시퀀스에 요소가 포함되지 않음
First 시퀀스에 일치하는 요소가 없습니다.
Single
SingleOrDefault
시퀀스에 일치하는 요소가 두 개 이상 포함되어 있습니다.

제거 하거나 예외를 처리 하는 방법을 호출 하는 특정 방법 및 애플리케이션의 가정에 따라 달라 집니다.

  • 빈 시퀀스에 대해 검사 않고 이러한 메서드 중 하나를 의도적으로 호출하는 경우 시퀀스가 비어 있지 않고 빈 시퀀스가 예기치 않은 것으로 가정합니다. 이 경우 예외를 catch하거나 다시 throw하는 것이 적절합니다.

  • 빈 시퀀스에 대해 검사 못한 경우 오버로드의 오버로드 Enumerable.Any 중 하나를 호출하여 시퀀스에 요소가 포함되어 있는지 여부를 확인할 수 있습니다.

    Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 처리할 데이터에 많은 요소가 포함되거나 시퀀스를 생성하는 작업이 비용이 많이 드는 경우 시퀀스를 생성하기 전에 메서드를 호출하면 성능이 향상될 수 있습니다.

  • 메서드Enumerable.FirstEnumerable.Last를 호출한 Enumerable.Single경우 시퀀스의 멤버 대신 기본값을 반환하는 대체 메서드(예: Enumerable.FirstOrDefault, Enumerable.LastOrDefault또는Enumerable.SingleOrDefault)를 대체할 수 있습니다.

이 예제에서는 추가 세부 정보를 제공합니다.

다음 예제에서는 메서드를 Enumerable.Average 사용하여 값이 4보다 큰 시퀀스의 평균을 계산합니다. 원래 배열의 값이 4를 초과하지 않으므로 시퀀스에 값이 포함되지 않으며 메서드가 예외를 InvalidOperationException throw합니다.

using System;
using System.Linq;

public class Example
{
   public static void Main()
   {
      int[] data = { 1, 2, 3, 4 };
      var average = data.Where(num => num > 4).Average();
      Console.Write("The average of numbers greater than 4 is {0}",
                    average);
   }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
//       at System.Linq.Enumerable.Average(IEnumerable`1 source)
//       at Example.Main()
open System
open System.Linq

let data = [| 1; 2; 3; 4 |]
let average = 
   data.Where(fun num -> num > 4).Average();
printfn $"The average of numbers greater than 4 is {average}"
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
//       at System.Linq.Enumerable.Average(IEnumerable`1 source)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example
   Public Sub Main()
      Dim data() As Integer = { 1, 2, 3, 4 }
      Dim average = data.Where(Function(num) num > 4).Average()
      Console.Write("The average of numbers greater than 4 is {0}",
                    average)
   End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
'       at System.Linq.Enumerable.Average(IEnumerable`1 source)
'       at Example.Main()

다음 예제와 같이 시퀀스를 처리하는 메서드를 호출하기 전에 시퀀스에 요소가 포함되어 있는지 여부를 확인하기 위해 메서드를 호출 Any 하여 예외를 제거할 수 있습니다.

using System;
using System.Linq;

public class EnumerableEx2
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };
        var moreThan4 = dbQueryResults.Where(num => num > 4);

        if (moreThan4.Any())
            Console.WriteLine("Average value of numbers greater than 4: {0}:",
                              moreThan4.Average());
        else
            // handle empty collection
            Console.WriteLine("The dataset has no values greater than 4.");
    }
}
// The example displays the following output:
//       The dataset has no values greater than 4.
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]
let moreThan4 = 
    dbQueryResults.Where(fun num -> num > 4)

if moreThan4.Any() then
    printfn $"Average value of numbers greater than 4: {moreThan4.Average()}:"
else
    // handle empty collection
    printfn "The dataset has no values greater than 4."

// The example displays the following output:
//       The dataset has no values greater than 4.
Imports System.Linq

Module Example1
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}
        Dim moreThan4 = dbQueryResults.Where(Function(num) num > 4)

        If moreThan4.Any() Then
            Console.WriteLine("Average value of numbers greater than 4: {0}:",
                             moreThan4.Average())
        Else
            ' Handle empty collection. 
            Console.WriteLine("The dataset has no values greater than 4.")
        End If
    End Sub
End Module
' The example displays the following output:
'       The dataset has no values greater than 4.

메서드는 Enumerable.First 시퀀스의 첫 번째 항목 또는 지정된 조건을 충족하는 시퀀스의 첫 번째 요소를 반환합니다. 시퀀스가 비어 있으므로 첫 번째 요소가 없으면 예외가 InvalidOperationException throw됩니다.

다음 예제 Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 에서는 dbQueryResults InvalidOperationException 배열에 4보다 큰 요소가 포함되어 있지 않으므로 메서드가 예외를 throw합니다.

using System;
using System.Linq;

public class EnumerableEx3
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var firstNum = dbQueryResults.First(n => n > 4);

        Console.WriteLine("The first value greater than 4 is {0}",
                          firstNum);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let firstNum = dbQueryResults.First(fun n -> n > 4)

printfn $"The first value greater than 4 is {firstNum}"

// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example2
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim firstNum = dbQueryResults.First(Function(n) n > 4)

        Console.WriteLine("The first value greater than 4 is {0}",
                        firstNum)
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains no matching element
'       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

지정된 값이나 기본값을 Enumerable.FirstOrDefault 반환하는 대신 Enumerable.First 메서드를 호출할 수 있습니다. 메서드가 시퀀스에서 첫 번째 요소를 찾지 못하면 해당 데이터 형식의 기본값을 반환합니다. 기본값은 null 참조 형식, 숫자 데이터 형식 및 형식 DateTime.MinValue 에 대한 DateTime 0입니다.

참고 항목

형식의 기본값이 시퀀스에서 유효한 값이 될 수 있으므로 메서드에서 반환 Enumerable.FirstOrDefault 된 값을 해석하는 것이 복잡할 수 있습니다. 이 경우 메서드를 호출하기 전에 메서드를 호출 Enumerable.AnyEnumerable.First 하여 시퀀스에 유효한 멤버가 있는지 여부를 확인합니다.

다음 예제에서는 메서드를 Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 호출하여 이전 예제에서 throw된 InvalidOperationException 예외를 방지합니다.

using System;
using System.Linq;

public class EnumerableEx4
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var firstNum = dbQueryResults.FirstOrDefault(n => n > 4);

        if (firstNum == 0)
            Console.WriteLine("No value is greater than 4.");
        else
            Console.WriteLine("The first value greater than 4 is {0}",
                              firstNum);
    }
}
// The example displays the following output:
//       No value is greater than 4.
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let firstNum = dbQueryResults.FirstOrDefault(fun n -> n > 4)

if firstNum = 0 then
    printfn "No value is greater than 4."
else
    printfn $"The first value greater than 4 is {firstNum}"

// The example displays the following output:
//       No value is greater than 4.
Imports System.Linq

Module Example3
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim firstNum = dbQueryResults.FirstOrDefault(Function(n) n > 4)

        If firstNum = 0 Then
            Console.WriteLine("No value is greater than 4.")
        Else
            Console.WriteLine("The first value greater than 4 is {0}",
                           firstNum)
        End If
    End Sub
End Module
' The example displays the following output:
'       No value is greater than 4.

하나의 요소 없이 시퀀스에서 Enumerable.Single 또는 Enumerable.SingleOrDefault를 호출합니다.

이 메서드는 Enumerable.Single 시퀀스의 유일한 요소 또는 지정된 조건을 충족하는 시퀀스의 유일한 요소를 반환합니다. 시퀀스에 요소가 없거나 둘 이상의 요소가 있는 경우 메서드는 예외를 InvalidOperationException throw합니다.

시퀀스에 요소가 없는 경우 예외를 throw하는 대신 메서드를 사용하여 Enumerable.SingleOrDefault 기본값을 반환할 수 있습니다. 그러나 Enumerable.SingleOrDefault 시퀀스에 둘 이상의 요소가 포함된 경우에도 메서드는 예외를 throw InvalidOperationException 합니다.

다음 표에서는 호출 및 메서드에 의해 throw된 예외 개체의 InvalidOperationExceptionEnumerable.Single 예외 메시지를 나열합니다 Enumerable.SingleOrDefault .

메서드 메시지
Single 시퀀스에 일치하는 요소가 없습니다.
Single
SingleOrDefault
시퀀스에 일치하는 요소가 두 개 이상 포함되어 있습니다.

다음 예제에서는 시퀀스에 4보다 큰 요소가 없으므로 메서드를 호출 Enumerable.Single 하면 예외가 throw InvalidOperationException 됩니다.

using System;
using System.Linq;

public class EnumerableEx5
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var singleObject = dbQueryResults.Single(value => value > 4);

        // Display results.
        Console.WriteLine("{0} is the only value greater than 4", singleObject);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let singleObject = dbQueryResults.Single(fun value -> value > 4)

// Display results.
printfn $"{singleObject} is the only value greater than 4"

// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example4
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim singleObject = dbQueryResults.Single(Function(value) value > 4)

        ' Display results.
        Console.WriteLine("{0} is the only value greater than 4",
                         singleObject)
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains no matching element
'       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

다음 예제에서는 메서드를 호출하여 시퀀스가 비어 있을 때 throw되는 예외를 Enumerable.SingleOrDefault 방지 InvalidOperationException 하려고 시도합니다. 그러나 이 시퀀스는 값이 2보다 큰 여러 요소를 반환하므로 예외도 throw합니다 InvalidOperationException .

using System;
using System.Linq;

public class EnumerableEx6
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var singleObject = dbQueryResults.SingleOrDefault(value => value > 2);

        if (singleObject != 0)
            Console.WriteLine("{0} is the only value greater than 2",
                              singleObject);
        else
            // Handle an empty collection.
            Console.WriteLine("No value is greater than 2");
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains more than one matching element
//       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let singleObject = dbQueryResults.SingleOrDefault(fun value -> value > 2)

if singleObject <> 0 then
    printfn $"{singleObject} is the only value greater than 2"
else
    // Handle an empty collection.
    printfn "No value is greater than 2"
    
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains more than one matching element
//       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example5
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim singleObject = dbQueryResults.SingleOrDefault(Function(value) value > 2)

        If singleObject <> 0 Then
            Console.WriteLine("{0} is the only value greater than 2",
                             singleObject)
        Else
            ' Handle an empty collection.
            Console.WriteLine("No value is greater than 2")
        End If
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains more than one matching element
'       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

메서드를 Enumerable.Single 호출하면 지정된 조건을 충족하는 시퀀스 또는 시퀀스에 하나의 요소만 포함되어 있다고 가정합니다. Enumerable.SingleOrDefault 는 0개 또는 1개의 결과가 있는 시퀀스를 가정하지만 더 이상 그렇지 않습니다. 이 가정이 의도적인 가정이고 이러한 조건이 충족되지 않는 경우 결과를 InvalidOperationException 다시 throw하거나 잡는 것이 적절합니다. 그렇지 않은 경우 또는 일부 빈도로 잘못된 조건이 발생할 것으로 예상되는 경우 다른 방법(예: FirstOrDefault 또는 Where)을 사용하는 Enumerable 것이 좋습니다.

동적 애플리케이션 간 do기본 필드 액세스

검색하려는 주소가 OpCodes.Ldflda 포함된 개체가 애플리케이션 내에 없는 경우 CIL(공용 중간 언어) 명령은 예외를 throw InvalidOperationException 합니다기본 코드가 실행되고 있습니다. 필드의 주소는 상주 하는 애플리케이션 도메인에서 액세스할 수만 있습니다.

InvalidOperationException 예외 throw

어떤 이유로 개체의 상태가 특정 메서드 호출을 지원하지 않는 경우에만 예외를 throw InvalidOperationException 해야 합니다. 즉, 메서드 호출은 일부 상황이나 컨텍스트에서 유효하지만 다른 경우에는 유효하지 않습니다.

메서드 호출 실패가 잘못된 인수로 인해 발생하는 경우 또는 ArgumentException 파생 클래스 ArgumentNullException 중 하나 또는 ArgumentOutOfRangeException그 대신 throw되어야 합니다.