この記事では、この API のリファレンス ドキュメントに補足的な解説を提供します。
InvalidOperationException は、メソッドの呼び出しに失敗した原因が無効な引数以外の理由で発生した場合に使用されます。 通常、オブジェクトの状態がメソッド呼び出しをサポートできない場合にスローされます。 たとえば、 InvalidOperationException 例外は、次のようなメソッドによってスローされます。
- IEnumerator.MoveNext 列挙子の作成後にコレクションのオブジェクトが変更された場合。 詳細については、「 反復処理中のコレクションの変更」を参照してください。
- ResourceSet.GetString メソッド呼び出しが行われる前にリソース セットが閉じている場合は 。
- XContainer.Addを指定すると、追加するオブジェクトが正しく構造化されていない XML ドキュメントになります。
- メイン スレッドまたは UI スレッドではないスレッドから UI を操作しようとするメソッド。
Von Bedeutung
InvalidOperationException例外はさまざまな状況でスローされる可能性があるため、Message プロパティによって返される例外メッセージを読み取る必要があります。
InvalidOperationException は、値が0x80131509を持つ HRESULT COR_E_INVALIDOPERATION
を使用します。
InvalidOperationExceptionのインスタンスの初期プロパティ値の一覧については、InvalidOperationExceptionコンストラクターを参照してください。
InvalidOperationException 例外の一般的な原因
次のセクションでは、アプリで例外がスローされる一般的なケース InvalidOperationException 示します。 問題の処理方法は、特定の状況によって異なります。 ただし、最も一般的な例外は開発者エラーの結果であり、 InvalidOperationException 例外を予測して回避できます。
UI 以外のスレッドからの UI スレッドの更新
多くの場合、ワーカー スレッドは、アプリケーションのユーザー インターフェイスに表示されるデータの収集を含むバックグラウンド処理を実行するために使用されます。 ただし、 Windows フォームや Windows Presentation Foundation (WPF) など、.NET 用のほとんどの GUI (グラフィカル ユーザー インターフェイス) アプリケーション フレームワークでは、UI (メインまたは UI スレッド) を作成および管理するスレッドからのみ GUI オブジェクトにアクセスできます。 UI スレッド以外のスレッドから UI 要素にアクセスしようとすると、 InvalidOperationException がスローされます。 例外メッセージのテキストを次の表に示します。
アプリケーションの種類 | メッセージ |
---|---|
WPF アプリ | 別のスレッドが所有しているため、呼び出し元のスレッドはこのオブジェクトにアクセスできません。 |
UWP アプリ | アプリケーションは、別のスレッド用にマーシャリングされたインターフェイスを呼び出しました。 |
Windows フォーム アプリ | スレッド間操作が無効です。作成されたスレッド以外のスレッドからアクセスされた "TextBox1" を制御します。 |
.NET の UI フレームワークは、UI 要素のメンバーへの呼び出しが UI スレッドで実行されているかどうかを確認するメソッドと、UI スレッドで呼び出しをスケジュールする他のメソッドを含む ディスパッチャー パターンを実装します。
- WPF アプリで、 Dispatcher.CheckAccess メソッドを呼び出して、UI 以外のスレッドでメソッドが実行されているかどうかを判断します。 メソッドが UI スレッドで実行されている場合は
true
を返し、それ以外の場合はfalse
返します。 Dispatcher.Invoke メソッドのいずれかのオーバーロードを呼び出して、UI スレッドでの呼び出しをスケジュールします。 - UWP アプリで、 CoreDispatcher.HasThreadAccess プロパティを調べて、UI 以外のスレッドでメソッドが実行されているかどうかを判断します。 CoreDispatcher.RunAsync メソッドを呼び出して、UI スレッドを更新するデリゲートを実行します。
- Windows フォーム アプリでは、 Control.InvokeRequired プロパティを使用して、メソッドが UI 以外のスレッドで実行されているかどうかを判断します。 Control.Invoke メソッドのいずれかのオーバーロードを呼び出して、UI スレッドを更新するデリゲートを実行します。
次の例は、作成したスレッド以外のスレッドから UI 要素を更新しようとしたときにスローされる InvalidOperationException 例外を示しています。 各例では、次の 2 つのコントロールを作成する必要があります。
-
textBox1
という名前のテキスト ボックス コントロール。 Windows フォーム アプリでは、その Multiline プロパティをtrue
に設定する必要があります。 -
threadExampleBtn
という名前のボタン コントロール。 この例では、ボタンのClick
イベントのハンドラー (ThreadsExampleBtn_Click
) を提供します。
いずれの場合も、 threadExampleBtn_Click
イベント ハンドラーは、 DoSomeWork
メソッドを 2 回呼び出します。 最初の呼び出しは同期的に実行され、成功します。 ただし、2 番目の呼び出しはスレッド プール スレッドで非同期的に実行されるため、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 フォーム アプリ
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 フォーム アプリの例外が排除されます。
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
ステートメントは、コレクションのメンバーを反復処理したり、個々の要素を読み取ったり変更したりするために使用されます。 ただし、コレクションの項目を追加または削除するために使用することはできません。 これを行うと、"Collection was modified; (コレクションが変更されました。)" のようなメッセージを含むInvalidOperationException例外がスローされます。列挙操作が実行されない可能性があります。"
次の例では、各整数の 2 乗をコレクションに追加しようとする整数のコレクションを反復処理します。 この例では、List<T>.Add メソッドの最初の呼び出しでInvalidOperationExceptionをスローします。
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()
アプリケーション ロジックに応じて、次の 2 つの方法のいずれかで例外を排除できます。
反復処理中に要素をコレクションに追加する必要がある場合は、
foreach
、for...in
、またはFor Each
ではなく、for
(F# でfor..to
) ステートメントを使用してインデックスを作成して反復処理できます。 次の例では、for ステートメントを使用して、コレクション内の数値の 2 乗をコレクションに追加します。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 を繰り返すか、または例のように配列内の要素の数を変数に割り当ててループの上限を確立することによって、コレクションを反復処理する前に反復回数を設定する必要があることに注意してください。 それ以外の場合、反復処理のたびに要素がコレクションに追加されると、無限ループが発生します。反復処理中にコレクションに要素を追加する必要がない場合は、コレクションの反復処理が完了したときに追加する一時コレクションに追加する要素を格納できます。 次の例では、この方法を使用して、コレクション内の数値の 2 乗を一時コレクションに追加し、コレクションを 1 つの配列オブジェクトに結合します。
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() メソッドなどの汎用の並べ替えメソッドでは、並べ替えるオブジェクトの少なくとも 1 つが IComparable<T> または IComparable インターフェイスを実装する必要があります。 そうでない場合は、コレクションまたは配列を並べ替えることができません。メソッドは InvalidOperationException 例外をスローします。 次の例では、Person
クラスを定義し、ジェネリック List<T> オブジェクトに 2 つのPerson
オブジェクトを格納し、並べ替えを試みます。 この例の出力に示すように、 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()
次の 3 つの方法のいずれかで例外を排除できます。
並べ替えようとしている型を所有できる場合 (つまり、ソース コードを制御する場合)、 IComparable<T> または IComparable インターフェイスを実装するように変更できます。 そのためには、 IComparable<T>.CompareTo メソッドまたは CompareTo メソッドを実装する必要があります。 インターフェイス実装を既存の型に追加することは、重大な変更ではありません。
次の例では、このアプローチを使用して、
Person
クラスのIComparable<T>実装を提供します。 引き続きコレクションまたは配列の一般的な並べ替えメソッドを呼び出すことができます。この例の出力に示すように、コレクションは正常に並べ替えられます。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> インターフェイスを実装する特殊な目的の並べ替えクラスを定義できます。 IComparer<T> パラメーターを含む
Sort
メソッドのオーバーロードを呼び出すことができます。 この方法は、複数の条件に基づいてオブジェクトを並べ替えることができる特殊な並べ替えクラスを開発する場合に特に便利です。次の例では、コレクションの並べ替えに使用するカスタム
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)
次の例では、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($"{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 許容<T> を基になる型にキャストする
基になる型にnull
Nullable<T>値をキャストしようとすると、InvalidOperationException例外がスローされ、"Nullable オブジェクトには値が必要です。
次の例では、Nullable(Of Integer)
値を含む配列を反復処理しようとすると、InvalidOperationException例外がスローされます。
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メソッドはシーケンスに対して操作を実行し、1 つの結果を返します。 これらのメソッドの一部のオーバーロードでは、シーケンスが空の場合に InvalidOperationException 例外がスローされますが、他のオーバーロードは null
を返します。
Enumerable.SingleOrDefault メソッドは、シーケンスに複数の要素が含まれている場合にも、InvalidOperationException例外をスローします。
注
InvalidOperationException例外をスローするメソッドのほとんどはオーバーロードです。 選択したオーバーロードの動作を理解していることを確認してください。
次の表に、一部のSystem.Linq.Enumerable メソッドの呼び出しによってスローされたInvalidOperationException例外オブジェクトからの例外メッセージを示します。
メソッド | メッセージ |
---|---|
Aggregate Average Last Max Min |
シーケンスに要素が含まれている |
First |
シーケンスに一致する要素が含まれています |
Single SingleOrDefault |
シーケンスに複数の一致する要素が含まれている |
例外を排除または処理する方法は、アプリケーションの想定と、呼び出す特定のメソッドによって異なります。
空のシーケンスを確認せずにこれらのメソッドのいずれかを意図的に呼び出すと、シーケンスが空ではなく、空のシーケンスが予期しない状況であると想定されます。 この場合、例外をキャッチまたは再スローすることが適切です。
空のシーケンスを確認できなかった場合は、 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 例外をスローします。
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 例外がスローされます。
次の例では、dbQueryResults 配列に 4 より大きい要素が含まれていないため、 Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) メソッドは InvalidOperationException 例外をスローします。
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.Firstの代わりに Enumerable.FirstOrDefault メソッドを呼び出して、指定した値または既定値を返すことができます。 メソッドがシーケンス内の最初の要素を見つけられない場合は、そのデータ型の既定値を返します。 既定値は、参照型の場合はnull
、数値データ型の場合は 0、DateTime型の場合はDateTime.MinValueです。
注
多くの場合、 Enumerable.FirstOrDefault メソッドによって返される値の解釈は、型の既定値がシーケンス内の有効な値にすることができるという事実によって複雑になります。 この場合は、Enumerable.First メソッドを呼び出す前に、Enumerable.Any メソッドを呼び出して、シーケンスに有効なメンバーがあるかどうかを判断します。
次の例では、 Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) メソッドを呼び出して、前の例でスローされた 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.
要素が 1 つもないシーケンスで Enumerable.Single または Enumerable.SingleOrDefault を呼び出す
Enumerable.Single メソッドは、シーケンスの唯一の要素、または指定した条件を満たすシーケンスの唯一の要素を返します。 シーケンス内に要素がない場合、または複数の要素がある場合、メソッドは InvalidOperationException 例外をスローします。
Enumerable.SingleOrDefault メソッドを使用すると、シーケンスに要素が含まれている場合に例外をスローするのではなく、既定値を返すことができます。 ただし、シーケンスに複数の要素が含まれている場合でも、 Enumerable.SingleOrDefault メソッドは InvalidOperationException 例外をスローします。
次の表に、Enumerable.Singleメソッドと Enumerable.SingleOrDefault メソッドの呼び出しによってスローされるInvalidOperationException例外オブジェクトからの例外メッセージを示します。
メソッド | メッセージ |
---|---|
Single |
シーケンスに一致する要素が含まれています |
Single SingleOrDefault |
シーケンスに複数の一致する要素が含まれている |
次の例では、シーケンスに 4 より大きい要素がないため、 Enumerable.Single メソッドの呼び出しによって 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($"{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()
次の例では、Enumerable.SingleOrDefault メソッドを呼び出して、シーケンスが空の場合にスローされるInvalidOperationException例外を回避します。 ただし、このシーケンスは値が 2 より大きい複数の要素を返すので、 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($"{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 メソッドを呼び出すと、指定した条件を満たすシーケンスまたはシーケンスに含まれる要素が 1 つだけであると見なされます。 Enumerable.SingleOrDefault は、0 個または 1 個の結果を持つシーケンスを想定しますが、それ以上の結果はありません。 この前提が意図的な前提であり、これらの条件が満たされていない場合は、結果として得られる InvalidOperationException を再スローまたはキャッチすることが適切です。 それ以外の場合、または何らかの頻度で無効な条件が発生すると予想される場合は、FirstOrDefaultやWhereなど、他のEnumerableメソッドの使用を検討する必要があります。
動的なアプリケーション間ドメイン フィールド アクセス
OpCodes.Ldflda共通中間言語 (CIL) 命令は、取得しようとしているアドレスを持つフィールドを含むオブジェクトが、コードを実行しているアプリケーション ドメイン内にない場合、InvalidOperationException例外をスローします。 フィールドのアドレスには、フィールドが存在するアプリケーション ドメインからのみアクセスできます。
InvalidOperationException 例外をスローする
何らかの理由でオブジェクトの状態が特定のメソッド呼び出しをサポートしていない場合にのみ、 InvalidOperationException 例外をスローする必要があります。 つまり、メソッド呼び出しは状況やコンテキストによっては有効ですが、他の状況では無効です。
メソッド呼び出しの失敗が無効な引数が原因である場合は、 ArgumentException またはその派生クラスの 1 つ ( ArgumentNullException または ArgumentOutOfRangeException) を代わりにスローする必要があります。
.NET