InvalidOperationException 클래스
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
메서드 호출이 개체의 현재 상태에 대해 유효하지 않을 때 throw되는 예외입니다.
public ref class InvalidOperationException : Exception
public ref class InvalidOperationException : SystemException
public class InvalidOperationException : Exception
public class InvalidOperationException : SystemException
[System.Serializable]
public class InvalidOperationException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class InvalidOperationException : SystemException
type InvalidOperationException = class
inherit Exception
type InvalidOperationException = class
inherit SystemException
[<System.Serializable>]
type InvalidOperationException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type InvalidOperationException = class
inherit SystemException
Public Class InvalidOperationException
Inherits Exception
Public Class InvalidOperationException
Inherits SystemException
- 상속
- 상속
- 파생
- 특성
설명
InvalidOperationException 는 메서드 호출 실패가 잘못된 인수 이외의 이유로 인해 발생하는 경우에 사용됩니다. 일반적으로 개체의 상태가 메서드 호출을 지원할 수 없을 때 throw됩니다. 예를 들어 예외 InvalidOperationException 는 다음과 같은 메서드에 의해 throw됩니다.
IEnumerator.MoveNext 컬렉션의 개체가 열거자를 만든 후 수정되면 입니다. 자세한 내용은 반복하는 동안 컬렉션 변경을 참조하세요.
ResourceSet.GetString 메서드를 호출하기 전에 리소스 집합이 닫혀 있으면 입니다.
XContainer.Add추가할 개체 또는 개체가 잘못 구조화된 XML 문서를 생성하면 입니다.
기본 또는 UI 스레드가 아닌 스레드에서 UI를 조작하려고 시도하는 메서드입니다.
중요
예외는 InvalidOperationException 다양한 상황에서 throw될 수 있으므로 속성에서 반환 Message 된 예외 메시지를 읽는 것이 중요합니다.
이 섹션의 내용은 다음과 같습니다.
InvalidOperationException 예외의 몇 가지 일반적인 원인
UI가 아닌 스레드에서 UI 스레드 업데이트
반복하는 동안 컬렉션 변경
개체를 비교할 수 없는 배열 또는 컬렉션 정렬
Null인 Null 허용<T> 를 기본 형식으로 캐스팅
빈 컬렉션에서 System.Linq.Enumerable 메서드 호출
하나의 요소가 없는 시퀀스에서 Enumerable.Single 또는 Enumerable.SingleOrDefault 호출
동적 애플리케이션 간 도메인 필드 액세스
InvalidOperationException 예외 throw
기타 정보
InvalidOperationException 예외의 몇 가지 일반적인 원인
다음 섹션에서는 예외가 앱에서 throw되는 InvalidOperationException 몇 가지 일반적인 사례를 보여 줍니다. 문제를 처리하는 방법은 특정 상황에 따라 달라집니다. 그러나 가장 일반적으로 예외는 개발자 오류로 인해 발생하며 예외를 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 앱에서는 해당 속성을true
로 Multiline 설정해야 합니다.라는 단추 컨트롤입니다
threadExampleBtn
. 이 예제에서는 단추의Click
이벤트에 대한 처리기ThreadsExampleBtn_Click
를 제공합니다.
각 경우에 threadExampleBtn_Click
이벤트 처리기는 메서드를 두 번 호출합니다 DoSomeWork
. 첫 번째 호출은 동기적으로 실행되고 성공합니다. 그러나 두 번째 호출은 스레드 풀 스레드에서 비동기적으로 실행되기 때문에 UI가 아닌 스레드에서 UI를 업데이트하려고 시도합니다. 이로 인해 예외가 발생합니다 InvalidOperationException .
WPF 및 UWP 앱
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;
}
Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) Handles threadExampleBtn.Click
textBox1.Text = String.Empty
textBox1.Text = "Simulating work on UI thread." + vbCrLf
DoSomeWork(20)
textBox1.Text += "Work completed..." + vbCrLf
textBox1.Text += "Simulating work on non-UI thread." + vbCrLf
Await Task.Factory.StartNew(Sub()
DoSomeWork(1000)
End Sub)
textBox1.Text += "Work completed..." + vbCrLf
End Sub
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim msg = String.Format("Some work completed in {0} ms.", milliseconds) + vbCrLf
textBox1.Text += msg
End Sub
다음 버전의 메서드는 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; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.CheckAccess()
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread",
milliseconds, If(uiAccess, String.Empty, "non-")) +
vbCrLf
If uiAccess Then
textBox1.Text += msg
Else
textBox1.Dispatcher.Invoke( Sub() textBox1.Text += msg)
End If
End Sub
다음 버전의 메서드는 DoSomeWork
UWP 앱에서 예외를 제거합니다.
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
bool uiAccess = textBox1.Dispatcher.HasThreadAccess;
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
await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.HasThreadAccess
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
milliseconds, If(uiAccess, String.Empty, "non-"))
If (uiAccess) Then
textBox1.Text += msg
Else
Await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() textBox1.Text += msg)
End If
End Sub
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 threadExampleBtn.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 Example
{
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 Example
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...in
또는For Each
대신foreach
( F#의 )for..to
문을 사용하여for
인덱스로 반복할 수 있습니다. 다음 예제에서는 for 문을 사용하여 컬렉션의 숫자 제곱을 컬렉션에 추가합니다.using System; using System.Collections.Generic; public class Example { 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 Example 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 Example { 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 Example 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 Person
{
public Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
public String FirstName { get; set; }
public String LastName { get; set; }
}
public class Example
{
public static void Main()
{
var people = new List<Person>();
people.Add(new Person("John", "Doe"));
people.Add(new Person("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 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
End Class
Module Example
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:
' 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> 구현하도록 수정할 수 있습니다. 이렇게 하려면 또는 메서드를 IComparable<T>.CompareTo 구현해야 CompareTo 합니다. 기존 형식에 인터페이스 구현을 추가하는 것은 호환성이 손상되는 변경이 아닙니다.
다음 예제에서는 이 방법을 사용하여 클래스에 IComparable<T> 대한 구현을
Person
제공합니다. 컬렉션 또는 배열의 일반 정렬 메서드를 계속 호출할 수 있으며 예제의 출력에서 볼 수 있듯이 컬렉션이 성공적으로 정렬됩니다.using System; using System.Collections.Generic; public class Person : IComparable<Person> { public Person(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 Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("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 Example 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
클래스를 개발하여 접근 방식을 사용합니다. 그런 다음 이 클래스의 instance 메서드에 List<T>.Sort(IComparer<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 PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("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 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 End Class Public Class PersonComparer : Implements IComparer(Of Person) Public Function Compare(x As Person, y As Person) As Integer _ Implements IComparer(Of Person).Compare Return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) End Function End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("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 Example { 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 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 End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("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 Person, y As Person) 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 Example
{
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 Example
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 Example
{
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 Example
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.LastEnumerable.Max, , Enumerable.Min, Enumerable.Single및 Enumerable.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하거나 다시 발생시키는 것이 적절합니다.
빈 시퀀스에 대한 검사 못한 경우 오버로드 오버 Enumerable.Any 로드 중 하나를 호출하여 시퀀스에 요소가 포함되어 있는지 여부를 확인할 수 있습니다.
팁
Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 처리할 데이터에 많은 요소가 포함될 수 있거나 시퀀스를 생성하는 작업이 비용이 많이 드는 경우 시퀀스를 생성하기 전에 메서드를 호출하면 성능이 향상될 수 있습니다.
, 또는 와 같은 Enumerable.First메서드를 호출한 경우 시퀀스의 멤버 대신 기본값을 반환하는 , Enumerable.LastOrDefault또는 Enumerable.SingleOrDefault와 같은 Enumerable.FirstOrDefault대체 메서드를 대체할 수 Enumerable.Single있습니다. Enumerable.Last
이 예제에서는 추가 세부 정보를 제공합니다.
다음 예제에서는 메서드를 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 Example
{
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 Example
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 Example
{
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 Example
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.First 를 Enumerable.FirstOrDefault 호출하여 지정된 또는 기본값을 반환할 수 있습니다. 메서드가 시퀀스에서 첫 번째 요소를 찾지 못하면 해당 데이터 형식의 기본값을 반환합니다. 기본값은 null
참조 형식, 숫자 데이터 형식의 경우 0, DateTime.MinValue 형식의 경우 입니다 DateTime .
참고
메서드에서 반환된 Enumerable.FirstOrDefault 값을 해석하는 것은 종종 형식의 기본값이 시퀀스에서 유효한 값일 수 있다는 사실 때문에 복잡합니다. 이 경우 메서드를 호출하기 전에 Enumerable.First 메서드를 Enumerable.Any 호출하여 시퀀스에 유효한 멤버가 있는지 여부를 확인합니다.
다음 예제에서는 메서드를 Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 호출하여 이전 예제에서 throw된 InvalidOperationException 예외를 방지합니다.
using System;
using System.Linq;
public class Example
{
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 Example
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합니다.
다음 표에서는 및 Enumerable.SingleOrDefault 메서드에 대한 호출에 InvalidOperationException 의해 throw된 예외 개체의 Enumerable.Single 예외 메시지를 나열합니다.
메서드 | 메시지 |
---|---|
Single |
시퀀스에 일치하는 요소가 없습니다. |
Single SingleOrDefault |
시퀀스에 일치하는 요소가 두 개 이상 포함되어 있습니다. |
다음 예제에서 메서드에 대한 Enumerable.Single 호출은 시퀀스에 4보다 큰 요소가 없기 때문에 예외를 throw InvalidOperationException 합니다.
using System;
using System.Linq;
public class Example
{
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 Example
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 Example
{
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 Example
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 다시 발생하거나 잡는 것이 적절합니다. 그렇지 않은 경우 또는 잘못된 조건이 빈도로 발생할 것으로 예상되는 경우 또는 Where와 같은 FirstOrDefault 다른 Enumerable 메서드를 사용하는 것이 좋습니다.
동적 애플리케이션 간 도메인 필드 액세스
합니다 OpCodes.Ldflda MSIL (intermediate language) 명령 throw 하는 Microsoft는 InvalidOperationException 필드는 검색 하려는 해당 주소를 포함 하는 개체 코드 실행 되는 애플리케이션 도메인 내에서 없는 경우 예외입니다. 필드의 주소는 상주 하는 애플리케이션 도메인에서 액세스할 수만 있습니다.
InvalidOperationException 예외 throw
어떤 이유로 개체의 상태가 특정 메서드 호출을 지원하지 않는 경우에만 예외를 throw InvalidOperationException 해야 합니다. 즉, 메서드 호출은 일부 상황이나 컨텍스트에서 유효하지만 다른 경우에는 유효하지 않습니다.
메서드 호출 실패가 잘못된 인수 ArgumentException 로 인한 경우 또는 파생 클래스 ArgumentNullException 중 하나 또는 ArgumentOutOfRangeException를 대신 throw해야 합니다.
기타 정보
InvalidOperationException 는 값이 0x80131509 HRESULT COR_E_INVALIDOPERATION 사용합니다.
인스턴스의 초기 속성 값의 목록을 InvalidOperationException, 참조는 InvalidOperationException 생성자입니다.
생성자
InvalidOperationException() |
InvalidOperationException 클래스의 새 인스턴스를 초기화합니다. |
InvalidOperationException(SerializationInfo, StreamingContext) |
사용되지 않습니다.
serialize된 데이터를 사용하여 InvalidOperationException 클래스의 새 인스턴스를 초기화합니다. |
InvalidOperationException(String) |
지정된 오류 메시지를 사용하여 InvalidOperationException 클래스의 새 인스턴스를 초기화합니다. |
InvalidOperationException(String, Exception) |
지정된 오류 메시지와 해당 예외의 원인인 내부 예외에 대한 참조를 사용하여 InvalidOperationException 클래스의 새 인스턴스를 초기화합니다. |
속성
Data |
예외에 대한 사용자 정의 정보를 추가로 제공하는 키/값 쌍 컬렉션을 가져옵니다. (다음에서 상속됨 Exception) |
HelpLink |
이 예외와 연결된 도움말 파일에 대한 링크를 가져오거나 설정합니다. (다음에서 상속됨 Exception) |
HResult |
특정 예외에 할당된 코드화된 숫자 값인 HRESULT를 가져오거나 설정합니다. (다음에서 상속됨 Exception) |
InnerException |
현재 예외를 발생시킨 Exception 인스턴스를 가져옵니다. (다음에서 상속됨 Exception) |
Message |
현재 예외를 설명하는 메시지를 가져옵니다. (다음에서 상속됨 Exception) |
Source |
오류를 발생시키는 애플리케이션 또는 개체의 이름을 가져오거나 설정합니다. (다음에서 상속됨 Exception) |
StackTrace |
호출 스택의 직접 실행 프레임 문자열 표현을 가져옵니다. (다음에서 상속됨 Exception) |
TargetSite |
현재 예외를 throw하는 메서드를 가져옵니다. (다음에서 상속됨 Exception) |
메서드
Equals(Object) |
지정된 개체가 현재 개체와 같은지 확인합니다. (다음에서 상속됨 Object) |
GetBaseException() |
파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다. (다음에서 상속됨 Exception) |
GetHashCode() |
기본 해시 함수로 작동합니다. (다음에서 상속됨 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
사용되지 않습니다.
파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다. (다음에서 상속됨 Exception) |
GetType() |
현재 인스턴스의 런타임 형식을 가져옵니다. (다음에서 상속됨 Exception) |
MemberwiseClone() |
현재 Object의 단순 복사본을 만듭니다. (다음에서 상속됨 Object) |
ToString() |
현재 예외에 대한 문자열 표현을 만들고 반환합니다. (다음에서 상속됨 Exception) |
이벤트
SerializeObjectState |
사용되지 않습니다.
예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다. (다음에서 상속됨 Exception) |
적용 대상
추가 정보
피드백
다음에 대한 사용자 의견 제출 및 보기