InvalidOperationException クラス

定義

オブジェクトの現在の状態に対して無効なメソッド呼び出しが行われた場合にスローされる例外。

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
継承
InvalidOperationException
派生
属性

注釈

InvalidOperationException は、無効な引数以外の理由でメソッドを呼び出すエラーが発生した場合に使用されます。 通常、オブジェクトの状態がメソッド呼び出しをサポートできない場合にスローされます。 たとえば、 InvalidOperationException 次のようなメソッドによって例外がスローされます。

  • IEnumerator.MoveNext 列挙子の作成後にコレクションのオブジェクトが変更された場合。 詳細については、「 反復処理中のコレクションの変更」を参照してください。

  • ResourceSet.GetString メソッド呼び出しが行われる前にリソース セットが閉じられた場合。

  • XContainer.Addを指定すると、追加するオブジェクトが正しく構造化されていない XML ドキュメントになります。

  • メイン スレッドまたは UI スレッドではないスレッドから UI を操作しようとするメソッド。

重要

例外は InvalidOperationException さまざまな状況でスローされる可能性があるため、プロパティによって Message 返される例外メッセージを読み取る必要があります。

このセクションの内容は次のとおりです。

InvalidOperationException 例外の一般的な原因
UI 以外のスレッドからの UI スレッドの更新
反復処理中にコレクションを変更する
オブジェクトを比較できない配列またはコレクションの並べ替え
null である Null 許容<T> を基になる型にキャストする
空のコレクションで System.Linq.Enumerable メソッドを呼び出す
要素が 1 つもないシーケンスで Enumerable.Single または Enumerable.SingleOrDefault を呼び出す
動的なアプリケーション間ドメイン フィールド アクセス
InvalidOperationException 例外のスロー
その他の情報

InvalidOperationException 例外の一般的な原因

次のセクションでは、アプリで例外がスローされる InvalidOperationException 一般的なケースをいくつか示します。 問題の処理方法は、特定の状況によって異なります。 ただし、最も一般的に、例外は開発者エラーの結果であり InvalidOperationException 、例外を予測して回避できます。

UI 以外のスレッドからの UI スレッドの更新

多くの場合、ワーカー スレッドは、アプリケーションのユーザー インターフェイスに表示されるデータの収集を含むバックグラウンド作業を実行するために使用されます。 ただし、 Windows フォームやWindows Presentation Foundation (WPF) など、.NET 用のほとんどの GUI (グラフィカル ユーザー インターフェイス) アプリケーション フレームワークでは、UI (メインまたは UI スレッド) を作成および管理するスレッドからのみ GUI オブジェクトにアクセスできます。 UI InvalidOperationException スレッド以外のスレッドから UI 要素にアクセスしようとするとスローされます。 例外メッセージのテキストを次の表に示します。

アプリケーションの種類 メッセージ
WPF アプリ 別のスレッドが所有しているため、呼び出し元のスレッドはこのオブジェクトにアクセスできません。
UWP アプリ アプリケーションは、別のスレッド用にマーシャリングされたインターフェイスを呼び出しました。
Windows フォーム アプリ スレッド間操作が無効: 作成されたスレッド以外のスレッドからアクセスされたコントロール 'TextBox1' です。

.NET の UI フレームワークは、UI 要素のメンバーへの呼び出しが UI スレッドで実行されているかどうかを確認するメソッドと、UI スレッドでの呼び出しをスケジュールする他のメソッドを含む ディスパッチャー パターンを実装します。

  • WPF アプリで、メソッドを Dispatcher.CheckAccess 呼び出して、UI 以外のスレッドでメソッドが実行されているかどうかを判断します。 メソッドが UI スレッドで実行されている場合は返され、それ以外のfalse場合は返trueされます。 メソッドのいずれかのオーバーロードを呼び出して、 Dispatcher.Invoke UI スレッドでの呼び出しをスケジュールします。

  • UWP アプリで、プロパティを CoreDispatcher.HasThreadAccess 確認して、UI 以外のスレッドでメソッドが実行されているかどうかを確認します。 メソッドを CoreDispatcher.RunAsync 呼び出して、UI スレッドを更新するデリゲートを実行します。

  • Windows フォーム アプリでは、プロパティをControl.InvokeRequired使用して、メソッドが UI 以外のスレッドで実行されているかどうかを判断します。 メソッドのいずれかのオーバーロードを呼び出して、 Control.Invoke UI スレッドを更新するデリゲートを実行します。

次の例では、UI 要素を InvalidOperationException 作成したスレッド以外のスレッドから UI 要素を更新しようとしたときにスローされる例外を示します。 各例では、次の 2 つのコントロールを作成する必要があります。

  • という名前 textBox1のテキスト ボックス コントロール。 Windows フォーム アプリでは、そのプロパティtrueMultiline .

  • という名前 threadExampleBtnのボタン コントロール。 この例では、 ThreadsExampleBtn_Clickボタンのイベントのハンドラーを提供します Click

いずれの場合も、イベント ハンドラーは threadExampleBtn_Click メソッドを DoSomeWork 2 回呼び出します。 最初の呼び出しは同期的に実行され、成功します。 ただし、2 番目の呼び出しは、スレッド プール スレッドで非同期的に実行されるため、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 フォーム アプリ

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

次のバージョンのメソッドは、DoSomeWorkWindows フォーム アプリの例外を排除します。

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#、F#、for...inまたはFor EachVisual Basic内のステートメントは、コレクションのメンバーを反復処理し、その個々の要素を読み取りまたは変更するために使用されます。 ただし、コレクションの項目を追加または削除するために使用することはできません。 これを行うと、"コレクションが変更されました" のようなメッセージで例外がスローInvalidOperationExceptionされます。列挙操作が実行されない可能性があります。"

次の例では、各整数の 2 乗をコレクションに追加しようとする整数のコレクションを反復処理します。 この例では、メソッドの最初の呼び出しで with InvalidOperationExceptionList<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()

アプリケーション ロジックに応じて、次の 2 つの方法のいずれかで例外を排除できます。

  • 反復処理中に要素をコレクションに追加する必要がある場合は、for``for..to(F#で) ステートメントの代わりに foreachfor...inまたは For Each. 次の例では、for ステートメントを使用して、コレクション内の数値の 2 乗をコレクションに追加します。

    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 まで繰り返すか、例のように配列内の要素の数を変数に割り当ててループの上限を確立する方法を使用して、コレクションを反復処理する前に反復回数を設定する必要があることに注意してください。 それ以外の場合、反復のたびに要素がコレクションに追加されると、無限ループが発生します。

  • 反復処理中にコレクションに要素を追加する必要がない場合は、コレクションの反復処理が完了したときに追加する一時コレクションに追加する要素を格納できます。 次の例では、この方法を使用して、コレクション内の数値の 2 乗を一時コレクションに追加し、コレクションを 1 つの配列オブジェクトに結合します。

    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
    

オブジェクトを比較できない配列またはコレクションの並べ替え

メソッドやメソッドなどのArray.Sort(Array)汎用の並べ替えメソッドでは、通常、並べ替えられるオブジェクトの少なくとも 1 つが、インターフェイスをIComparable実装IComparable<T>する必要List<T>.Sort()があります。 存在しない場合は、コレクションまたは配列を並べ替えることができません。メソッドは例外を InvalidOperationException スローします。 次の例では、クラスをPerson定義し、ジェネリック List<T> オブジェクトに 2 つのPersonオブジェクトを格納し、並べ替えを試みます。 この例の出力に示すように、メソッドのList<T>.Sort()呼び出しで .InvalidOperationException

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()

例外は、次の 3 つの方法のいずれかで排除できます。

  • 並べ替えしようとしている型を所有できる場合 (つまり、ソース コードを制御する場合)、インターフェイスをIComparable実装IComparable<T>するように変更できます。 これには、メソッドまたはメソッドを実装するIComparable<T>.CompareToCompareTo必要があります。 既存の型にインターフェイス実装を追加することは、重大な変更ではありません。

    次の例では、このアプローチを使用してクラスの 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 クラスを開発することで、このアプローチを使用します。 その後、このクラスのインスタンスをメソッドに 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)  
    

    次の例では、デリゲートシグネチャに一致するメソッドを 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 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 許容<T> 値を基になる型にキャストする

基になる型に値をキャスト Nullable<T> しようとすると、例外が null スロー InvalidOperationException され、エラー メッセージが表示されます。"Null 許容オブジェクトには値が必要です。

次の例では、値を InvalidOperationException 含む配列を反復処理しようとしたときに例外を Nullable(Of Integer) スローします。

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.AverageEnumerable.FirstEnumerable.LastEnumerable.SingleEnumerable.MaxEnumerable.Min、およびEnumerable.SingleOrDefaultメソッドはEnumerable.Aggregate、シーケンスに対して操作を実行し、1 つの結果を返します。 これらのメソッドの一部のオーバーロードでは、シーケンスが空のときに例外がスロー InvalidOperationException されますが、他のオーバーロードは返されます null。 このメソッドは Enumerable.SingleOrDefaultInvalidOperationException シーケンスに複数の要素が含まれている場合にも例外をスローします。

注意

例外をスロー InvalidOperationException するメソッドのほとんどはオーバーロードです。 選択したオーバーロードの動作を理解していることを確認してください。

次の表は、一部のメソッドの呼び出しによってスローされた例外オブジェクトからの InvalidOperationException 例外メッセージの一覧 System.Linq.Enumerable です。

メソッド メッセージ
Aggregate
Average
Last
Max
Min
シーケンスに要素が含まれている
First シーケンスに一致する要素が含まれている
Single
SingleOrDefault
シーケンスに複数の一致する要素が含まれている

例外を排除または処理する方法は、アプリケーションの前提条件と、呼び出す特定のメソッドによって異なります。

  • 空のシーケンスを確認せずにこれらのメソッドのいずれかを意図的に呼び出すと、シーケンスが空ではなく、空のシーケンスが予期しない状態であると仮定します。 この場合、例外をキャッチまたは再スローすることが適切です。

  • 空のシーケンスを確認できなかった場合は、オーバーロードのいずれかのオーバーロード Enumerable.Any を呼び出して、シーケンスに要素が含まれているかどうかを判断できます。

    ヒント

    シーケンスを Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 生成する前にメソッドを呼び出すと、処理するデータに多数の要素が含まれている可能性がある場合や、シーケンスを生成する操作にコストがかかる場合にパフォーマンスが向上する可能性があります。

  • (またはEnumerable.Single) などのEnumerable.FirstEnumerable.Lastメソッドを呼び出した場合は、Enumerable.FirstOrDefaultEnumerable.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 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 スローされます。

次の例では、 Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) dbQueryResults 配列に 4 より大きい要素が含まれていないため、メソッドは例外をスロー InvalidOperationException します。

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.FirstOrDefault 返す代 Enumerable.First わりに、メソッドを呼び出すことができます。 メソッドがシーケンス内の最初の要素を見つけられない場合は、そのデータ型の既定値を返します。 既定値は、参照型、数値データ型の場合は 0、DateTime.MinValue型の場合は null DateTime 0 です。

注意

メソッドによって返される値の Enumerable.FirstOrDefault 解釈は、多くの場合、型の既定値がシーケンス内の有効な値になる可能性があることによって複雑になります。 この場合、メソッドを呼び出して、メソッドを Enumerable.Any 呼び出す Enumerable.First 前にシーケンスに有効なメンバーがあるかどうかを判断します。

次の例では、前の Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) 例でスローされた例外を 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.

要素が 1 つもないシーケンスで Enumerable.Single または Enumerable.SingleOrDefault を呼び出す

このメソッドは Enumerable.Single 、シーケンスの唯一の要素、または指定された条件を満たすシーケンスの唯一の要素を返します。 シーケンス内に要素がない場合、または複数の要素がある場合、メソッドは例外を InvalidOperationException スローします。

シーケンスに要素が Enumerable.SingleOrDefault 含まれている場合に例外をスローする代わりに、このメソッドを使用して既定値を返すことができます。 ただし、シーケンスに Enumerable.SingleOrDefault 複数の InvalidOperationException 要素が含まれている場合でも、メソッドは例外をスローします。

次の表に、メソッドの呼び出しによってスローされた例外オブジェクトからのInvalidOperationException例外メッセージをEnumerable.SingleEnumerable.SingleOrDefault示します。

メソッド メッセージ
Single シーケンスに一致する要素が含まれている
Single
SingleOrDefault
シーケンスに複数の一致する要素が含まれている

次の例では、シーケンスに Enumerable.Single 4 より大きい要素がないため、メソッドの呼び出しで例外がスロー 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()

次の例では、代わりにメソッドを InvalidOperationException 呼び出すことで、シーケンスが空のときにスローされる例外を Enumerable.SingleOrDefault 回避しようとしています。 ただし、このシーケンスは、値が 2 より大きい複数の要素を返すので、例外もスローします 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 呼び出すと、指定した条件を満たすシーケンスまたはシーケンスに含まれる要素が 1 つだけであると見なされます。 Enumerable.SingleOrDefault は、0 個または 1 個の結果を持つシーケンスを想定しますが、それ以上の結果はありません。 この仮定が意図的な前提であり、これらの条件が満たされない場合は、結果 InvalidOperationException を再スローまたはキャッチすることが適切です。 それ以外の場合、または何らかの頻度で無効な条件が発生すると予想される場合は、他のEnumerable方法 (例: FirstOrDefault .Where

動的なアプリケーション間ドメイン フィールド アクセス

OpCodes.Ldflda取得しようとしているフィールドを含むオブジェクトが、コードが実行されているアプリケーション ドメイン内にない場合、Microsoft 中間言語 (MSIL) 命令は例外をスローInvalidOperationExceptionします。 フィールドのアドレスには、フィールドが存在するアプリケーション ドメインからのみアクセスできます。

InvalidOperationException 例外のスロー

何らかの理由で InvalidOperationException オブジェクトの状態が特定のメソッド呼び出しをサポートしていない場合にのみ、例外をスローする必要があります。 つまり、メソッド呼び出しは状況やコンテキストによっては有効ですが、他の状況では無効です。

メソッドの呼び出しエラーが無効な引数が原因である場合は、 ArgumentException その派生クラスの 1 つ、または派生クラスの 1 つ、 ArgumentNullException または ArgumentOutOfRangeException、代わりにスローする必要があります。

その他の情報

InvalidOperationException は、0x80131509値を持つ HRESULT COR_E_INVALIDOPERATIONを使用します。

インスタンスの初期プロパティ値の一覧についてはInvalidOperationExceptionを参照してください、InvalidOperationExceptionコンス トラクター。

コンストラクター

InvalidOperationException()

InvalidOperationException クラスの新しいインスタンスを初期化します。

InvalidOperationException(SerializationInfo, StreamingContext)

シリアル化したデータを使用して、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

現在の例外がスローされたメソッドを取得します。

(継承元 Exception)

メソッド

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetBaseException()

派生クラスでオーバーライドされた場合、それ以後に発生する 1 つ以上の例外の根本原因である Exception を返します。

(継承元 Exception)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetObjectData(SerializationInfo, StreamingContext)

派生クラスでオーバーライドされた場合は、その例外に関する情報を使用して SerializationInfo を設定します。

(継承元 Exception)
GetType()

現在のインスタンスのランタイム型を取得します。

(継承元 Exception)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在の例外の文字列形式を作成して返します。

(継承元 Exception)

events

SerializeObjectState
互換性のために残されています。

例外がシリアル化され、例外に関するシリアル化されたデータを含む例外状態オブジェクトが作成されたときに発生します。

(継承元 Exception)

適用対象

こちらもご覧ください