이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.
InvalidOperationException 잘못된 인수 이외의 이유로 인해 메서드를 호출하지 못한 경우에 사용됩니다. 일반적으로, 개체의 상태가 메서드 호출을 지원할 수 없을 때 발생합니다. 예를 들어, InvalidOperationException 예외는 다음과 같은 메서드에 의해 throw됩니다.
- IEnumerator.MoveNext 열거자를 만든 후 컬렉션의 개체가 수정되는 경우입니다. 자세한 내용은 반복하는 동안 컬렉션 변경참조하세요.
- 메서드를 호출하기 전에 리소스 집합이 닫혀 있는지 ResourceSet.GetString.
- XContainer.Add추가할 개체가 잘못 구조화된 XML 문서를 생성할 경우
- 기본 또는 UI 스레드가 아닌 스레드에서 UI를 조작하려고 시도하는 메서드입니다.
중요합니다
InvalidOperationException 예외는 다양한 상황에서 throw될 수 있으므로 Message 속성에서 반환된 예외 메시지를 읽는 것이 중요합니다.
InvalidOperationException는 값이 0x80131509인 HRESULT COR_E_INVALIDOPERATION
을 사용합니다.
InvalidOperationException인스턴스의 초기 속성 값 목록은 InvalidOperationException 생성자를 참조하세요.
InvalidOperationException 예외의 일반적인 원인
다음 섹션에서는 앱에서 InvalidOperationException 예외가 발생하는 몇 가지 일반적인 사례와 그 원인을 설명합니다. 문제를 처리하는 방법은 특정 상황에 따라 달라집니다. 그러나 가장 일반적으로 예외는 개발자 오류로 인해 발생하며 InvalidOperationException 예외를 예상 및 방지할 수 있습니다.
비 UI 스레드에서 UI 스레드 업데이트
종종 작업자 스레드는 애플리케이션의 사용자 인터페이스에 표시할 데이터 수집을 포함하는 일부 백그라운드 작업을 수행하는 데 사용됩니다. 하지만. Windows Forms 및 WPF(Windows Presentation Foundation)와 같은 .NET용 대부분의 GUI(그래픽 사용자 인터페이스) 애플리케이션 프레임워크를 사용하면 UI(기본 또는 UI 스레드)를 만들고 관리하는 스레드에서만 GUI 개체에 액세스할 수 있습니다. UI 스레드가 아닌 다른 스레드에서 UI 요소에 액세스하려고 하면 오류 InvalidOperationException이(가) 던져집니다. 예외 메시지의 텍스트는 다음 표에 나와 있습니다.
애플리케이션 유형 | 메시지 |
---|---|
WPF 앱 | 호출 스레드는 다른 스레드가 소유하므로 이 개체에 액세스할 수 없습니다. |
UWP 앱 | 애플리케이션은 다른 스레드에 대해 마샬링된 인터페이스를 호출했습니다. |
Windows Forms 앱 | 스레드 간 작업이 유효하지 않습니다: 'TextBox1' 제어가 생성된 스레드가 아닌 다른 스레드에서 액세스되었습니다. |
.NET용 UI 프레임워크는 UI 요소의 멤버에 대한 호출이 UI 스레드에서 실행되고 있는지 여부를 확인하는 메서드와 UI 스레드에서 호출을 예약하는 다른 메서드를 포함하는 디스패처 패턴을 구현합니다.
- WPF 앱에서 Dispatcher.CheckAccess 메서드를 호출하여 메서드가 UI가 아닌 스레드에서 실행 중인지 확인합니다. 메서드가 UI 스레드에서 실행 중이면
true
반환하고, 그렇지 않으면false
. Dispatcher.Invoke 메서드의 오버로드 중 하나를 호출하여 UI 스레드에서 호출을 예약합니다. - UWP 앱에서 CoreDispatcher.HasThreadAccess 속성을 확인하여 메서드가 UI가 아닌 스레드에서 실행 중인지 확인합니다. CoreDispatcher.RunAsync 메서드를 호출하여 UI 스레드를 업데이트하는 대리자를 실행합니다.
- Windows Forms 앱에서 Control.InvokeRequired 속성을 사용하여 메서드가 UI가 아닌 스레드에서 실행 중인지 확인합니다. Control.Invoke 메서드의 오버로드 중 하나를 호출하여 UI 스레드를 업데이트하는 대리자를 실행합니다.
다음 예제에서는 UI 요소를 만든 스레드가 아닌 스레드에서 UI 요소를 업데이트하려고 할 때 throw되는 InvalidOperationException 예외를 보여 줍니다. 각 예제에서는 두 개의 컨트롤을 만들어야 합니다.
- 이름이
textBox1
텍스트 상자 컨트롤입니다. Windows Forms 앱에서는 Multiline 속성을true
로 설정해야 합니다. - 이름이
threadExampleBtn
인 버튼 컨트롤입니다. 이 예제에서는 단추의ThreadsExampleBtn_Click
이벤트에 대한 처리기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
컬렉션을 반복하면서 변경하기
C#의 foreach
문, F#의 for...in
또는 Visual Basic의 For Each
문은 컬렉션의 멤버를 반복하고 개별 요소를 읽거나 수정하는 데 사용됩니다. 그러나 컬렉션에서 항목을 추가하거나 제거하는 데는 사용할 수 없습니다. 이렇게 하면 예외 InvalidOperationException이 발생하고, 메시지는 "컬렉션이 수정되었습니다; 열거형 작업은 실행되지 않을 수 있습니다."와 비슷합니다.
다음 예제에서는 컬렉션에 각 정수의 제곱을 추가하려고 시도하는 정수 컬렉션을 반복합니다. 예제는 InvalidOperationException 메서드에 대한 첫 번째 호출 시 List<T>.Add을 throw합니다.
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($"{number}^{square}");
Console.WriteLine($"Adding {square} to the collection...");
Console.WriteLine();
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
,for..to
또는foreach
대신for...in
(F#의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($"{numbers[ctr]}^{square}"); Console.WriteLine($"Adding {square} to the collection..."); Console.WriteLine(); 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
루프 내에서 루프를 적절하게 종료하는 카운터를 사용하거나, 뒤로 반복하거나,
Count
- 1에서 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
개체를 비교할 수 없는 배열 또는 컬렉션 정렬
Array.Sort(Array) 메서드 또는 List<T>.Sort() 메서드와 같은 범용 정렬 메서드는 일반적으로 정렬할 개체 중 하나 이상이 IComparable<T> 또는 IComparable 인터페이스를 구현해야 합니다. 그렇지 않은 경우 컬렉션 또는 배열을 정렬할 수 없으며 메서드는 InvalidOperationException 예외를 throw합니다. 다음 예제에서는 Person
클래스를 정의하고, 제네릭 Person
개체에 두 개의 List<T> 개체를 저장하고, 정렬을 시도합니다. 예제의 출력 결과에서 보이듯이, List<T>.Sort() 메서드를 호출하면 InvalidOperationException오류가 발생합니다.
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($"{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<T> 또는 IComparable 인터페이스를 구현하도록 수정할 수 있습니다. 이렇게 하려면 IComparable<T>.CompareTo 또는 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($"{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> 메서드의 오버로드를 호출할 수 있습니다. 이 방법은 여러 조건에 따라 개체를 정렬할 수 있는 특수 정렬 클래스를 개발하려는 경우에 특히 유용합니다.다음 예제에서는
PersonComparer
컬렉션을 정렬하는 데 사용되는 사용자 지정Person
클래스를 개발하여 이 방법을 사용합니다. 그런 다음 이 클래스의 인스턴스를 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($"{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)
다음 예제에서는
PersonComparison
대리자 서명과 일치하는 Comparison<T> 메서드를 정의하여 이 방법을 사용합니다. 그런 다음 이 대리자를 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($"{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
Nullable<T>가 null일 때 이를 기본 형식으로 캐스팅
기본 형식에 캐스팅되는 Nullable<T>null
값을 시도하면 InvalidOperationException 예외가 발생하고 오류 메시지로 "널 허용 개체는 값을 가져야 합니다."가 표시됩니다.
다음 예제에서는 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()
예외를 방지하려면 다음을 수행합니다.
-
Nullable<T>.HasValue 속성을 사용하여
null
않은 요소만 선택합니다. -
Nullable<T>.GetValueOrDefault 오버로드 중 하나를 호출하여
null
값의 기본값을 제공합니다.
다음 예제에서는 둘 다 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.Aggregate, Enumerable.Average, Enumerable.First, Enumerable.Last, Enumerable.Max, Enumerable.Min, Enumerable.Single및 Enumerable.SingleOrDefault 메서드는 시퀀스에 대한 작업을 수행하고 단일 결과를 반환합니다. 이러한 메서드의 일부 오버로드는 시퀀스가 비어 있을 때 InvalidOperationException 예외를 throw하고 다른 오버로드는 null
반환합니다. 또한 Enumerable.SingleOrDefault 메서드는 시퀀스에 둘 이상의 요소가 포함된 경우 InvalidOperationException 예외를 throw합니다.
비고
InvalidOperationException 예외를 throw하는 대부분의 메서드는 오버로드입니다. 선택한 오버로드의 동작을 이해해야 합니다.
다음 표에서는 일부 InvalidOperationException 메서드를 호출하여 throw된 System.Linq.Enumerable 예외 개체의 예외 메시지를 나열합니다.
메서드 | 메시지 |
---|---|
Aggregate Average Last Max Min |
시퀀스에 요소가 없습니다. |
First |
시퀀스에 일치하는 요소 없음 |
Single SingleOrDefault |
Sequence에는 일치하는 요소가 둘 이상 |
예외를 제거하거나 처리하는 방법은 애플리케이션의 가정과 호출하는 특정 방법에 따라 달라집니다.
빈 시퀀스를 확인하지 않고 이러한 메서드 중 하나를 의도적으로 호출하는 경우 시퀀스가 비어 있지 않고 빈 시퀀스가 예기치 않은 것으로 가정합니다. 이 경우 예외를 포착하거나 다시 던지는 것이 적절합니다.
빈 시퀀스를 확인하지 못한 경우 Enumerable.Any 오버로드의 오버로드 중 하나를 호출하여 시퀀스에 요소가 포함되어 있는지 여부를 확인할 수 있습니다.
팁 (조언)
시퀀스를 생성하기 전에 Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 메서드를 호출하면 처리할 데이터에 많은 요소가 포함되거나 시퀀스를 생성하는 작업이 비용이 많이 드는 경우 성능이 향상될 수 있습니다.
Enumerable.First, Enumerable.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: {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됩니다.
다음 예제에서는 dbQueryResults 배열에 4보다 큰 요소가 포함되지 않으므로 Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 메서드가 InvalidOperationException 예외를 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 {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
, 숫자 데이터 형식의 경우 0, DateTime.MinValue 형식에 대한 DateTime.
비고
Enumerable.FirstOrDefault 메서드에서 반환된 값을 해석하는 것은 종종 형식의 기본값이 시퀀스에서 유효한 값일 수 있기 때문에 복잡합니다. 이 경우 Enumerable.Any 메서드를 호출하여 Enumerable.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 {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 메서드는 시퀀스에 둘 이상의 요소가 포함된 경우에도 InvalidOperationException 예외를 throw합니다.
다음 표에서는 InvalidOperationException 및 Enumerable.Single 메서드 호출에 의해 throw된 Enumerable.SingleOrDefault 예외 개체의 예외 메시지를 나열합니다.
메서드 | 메시지 |
---|---|
Single |
시퀀스에 일치하는 요소 없음 |
Single SingleOrDefault |
Sequence에는 일치하는 요소가 둘 이상 |
다음 예제에서는 시퀀스에 4보다 큰 요소가 없으므로 Enumerable.Single 메서드를 호출하면 InvalidOperationException 예외가 throw됩니다.
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($"{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 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()
다음 예제에서는 시퀀스가 비어 있을 때 InvalidOperationException 예외가 throw되지 않도록 Enumerable.SingleOrDefault 메서드를 호출합니다. 그러나 이 시퀀스는 값이 2보다 큰 여러 요소를 반환하므로 InvalidOperationException 예외도 throw합니다.
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($"{singleObject} is the only value greater than 2");
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하거나 잡는 것이 적절합니다. 그렇지 않은 경우 또는 일부 빈도로 잘못된 조건이 발생할 것으로 예상되는 경우 Enumerable 또는 FirstOrDefault같은 다른 Where 메서드를 사용하는 것이 좋습니다.
동적 애플리케이션 간 도메인 필드 액세스
검색하려는 주소가 있는 필드가 포함된 개체가 코드가 실행되는 애플리케이션 도메인 내에 없는 경우 OpCodes.Ldflda CIL(공용 중간 언어) 명령은 InvalidOperationException 예외를 throw합니다. 필드의 주소는 필드가 있는 애플리케이션 도메인에서만 액세스할 수 있습니다.
InvalidOperationException 예외를 던지다
어떤 이유로 개체의 상태가 특정 메서드 호출을 지원하지 않는 경우에만 InvalidOperationException 예외를 throw해야 합니다. 즉, 메서드 호출은 일부 상황이나 컨텍스트에서 유효하지만 다른 경우에는 유효하지 않습니다.
메서드 호출 실패가 잘못된 인수로 인해 발생하는 경우 ArgumentException 또는 파생 클래스 중 하나(ArgumentNullException 또는 ArgumentOutOfRangeException)를 대신 throw해야 합니다.
.NET