InvalidOperationException InvalidOperationException InvalidOperationException InvalidOperationException Class

定義

當方法呼叫對物件的目前狀態無效時所擲回的例外狀況。The exception that is thrown when a method call is invalid for the object's current state.

public ref class InvalidOperationException : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class InvalidOperationException : SystemException
type InvalidOperationException = class
    inherit SystemException
Public Class InvalidOperationException
Inherits SystemException
繼承
InvalidOperationExceptionInvalidOperationExceptionInvalidOperationExceptionInvalidOperationException
衍生
屬性

備註

InvalidOperationException在無法叫用方法的情況下, 會因無效引數以外的原因而使用。InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. 一般而言, 當物件的狀態無法支援方法呼叫時, 就會擲回此例外狀況。Typically, it is thrown when the state of an object cannot support the method call. 例如, 方法會InvalidOperationException擲回例外狀況, 例如:For example, an InvalidOperationException exception is thrown by methods such as:

重要

因為例外狀況可能會在各種不同的情況下擲回, 所以請務必閱讀Message屬性所傳回的例外狀況訊息。 InvalidOperationExceptionBecause the InvalidOperationException exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the Message property.

本節內容:In this section:

InvalidOperationException 例外狀況的一些常見原因 Some common causes of InvalidOperationException exceptions
從非 UI 執行緒更新 UI 執行緒Updating a UI thread from a non-UI thread
在反覆運算時變更集合Changing a collection while iterating it
排序無法比較其物件的陣列或集合Sorting an array or collection whose objects cannot be compared
將 null 的>T轉換為其基礎類型< Casting a Nullable<T> that is null to its underlying type
在空集合上呼叫 System.object 方法Calling a System.Linq.Enumerable method on an empty collection
在沒有一個元素的序列上呼叫可列舉的 SingleOrDefault。Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
動態跨應用程式域欄位存取Dynamic cross-application domain field access
擲回 InvalidOperationException 例外狀況Throwing an InvalidOperationException exception
其他資訊Miscellaneous information

InvalidOperationException 例外狀況的一些常見原因Some common causes of InvalidOperationException exceptions

下列各節顯示在InvalidOperationException應用程式中擲回例外狀況的一些常見案例。The following sections show how some common cases in which in InvalidOperationException exception is thrown in an app. 處理問題的方式取決於特定的情況。How you handle the issue depends on the specific situation. 不過, 最常見的例外狀況是由開發人員錯誤所造成InvalidOperationException , 而例外狀況也可以被預期和避免。Most commonly, however, the exception results from developer error, and the InvalidOperationException exception can be anticipated and avoided.

從非 UI 執行緒更新 UI 執行緒Updating a UI thread from a non-UI thread

工作者執行緒通常是用來執行一些背景工作, 包括收集要在應用程式的使用者介面中顯示的資料。Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. 不過.However. 大部分適用于 .NET Framework 的 GUI (圖形化使用者介面) 應用程式架構, 例如 Windows Forms 和 Windows Presentation Foundation (WPF), 可讓您只從建立及管理 UI 的執行緒 (主要或 UI 執行緒) 存取 GUI 物件。most GUI (graphical user interface) application frameworks for the .NET Framework, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). 當您嘗試從 ui 執行緒以外的執行緒存取 ui 元素時,就會擲回。InvalidOperationExceptionAn InvalidOperationException is thrown when you try to access a UI element from a thread other than the UI thread. 下表顯示例外狀況訊息的文字。The text of the exception message is shown in the following table.

應用程式類型Application Type 訊息Message
WPF 應用程式WPF app 呼叫執行緒無法存取此物件, 因為有不同的執行緒擁有它。The calling thread cannot access this object because a different thread owns it.
UWP 應用程式UWP app 應用程式呼叫的介面已針對不同的執行緒封送處理。The application called an interface that was marshaled for a different thread.
Windows Forms 應用程式Windows Forms app 跨執行緒作業無效:控制項 ' TextBox1 ' 是從建立它的執行緒以外的執行緒進行存取。Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.

.NET Framework 的 UI 架構會執行一個發送器模式, 其中包含一個方法, 可檢查是否正在 ui 執行緒上執行對 ui 元素成員的呼叫, 以及在 ui 執行緒上排定呼叫的其他方法:UI frameworks for the .NET Framework implement a dispatcher pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread:

  • 在 WPF 應用程式中, Dispatcher.CheckAccess呼叫方法來判斷方法是否在非 UI 執行緒上執行。In WPF apps, call the Dispatcher.CheckAccess method to determine if a method is running on a non-UI thread. 如果方法是在 UI 執行緒上執行, 則會傳回false , 否則會傳回。 trueIt returns true if the method is running on the UI thread and false otherwise. 呼叫Dispatcher.Invoke方法的其中一個多載, 以排程 UI 執行緒上的呼叫。Call one of the overloads of the Dispatcher.Invoke method to schedule the call on the UI thread.

  • 在 UWP 應用程式中, 呼叫CoreDispatcher. HasThreadAccess方法, 以判斷方法是否正在非 UI 執行緒上執行。In UWP apps, call the CoreDispatcher.HasThreadAccess method to determine if a method is running on a non-UI thread. 呼叫CoreDispatcher. RunAsync方法, 以執行可更新 UI 執行緒的委派。Call the CoreDispatcher.RunAsync method to execute a delegate that updates the UI thread. 使用Use the

  • 在 Windows Forms 應用程式中, Control.InvokeRequired使用屬性來判斷方法是否在非 UI 執行緒上執行。In Windows Forms apps, use the Control.InvokeRequired property to determine if a method is running on a non-UI thread. 呼叫Control.Invoke方法的其中一個多載, 以執行可更新 UI 執行緒的委派。Call one of the overloads of the Control.Invoke method to execute a delegate that updates the UI thread.

下列範例說明當您InvalidOperationException嘗試從非建立 UI 專案的執行緒 (而不是從建立它的執行緒) 進行更新時, 所擲回的例外狀況。The following examples illustrate the InvalidOperationException exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. 每個範例都需要您建立兩個控制項:Each example requires that you create two controls:

  • 名為textBox1的文字方塊控制項。A text box control named textBox1. 在 Windows Forms 應用程式中, 您應該將Multiline其屬性true設為。In a Windows Forms app, you should set its Multiline property to true.

  • 名為threadExampleBtn的按鈕控制項。A button control named threadExampleBtn. 此範例會為按鈕的ThreadsExampleBtn_Click Click事件提供處理常式。The example provides a handler, ThreadsExampleBtn_Click, for the button's Click event.

在每個案例中threadExampleBtn_Click , 事件處理常式DoSomeWork都會呼叫方法兩次。In each case, the threadExampleBtn_Click event handler calls the DoSomeWork method twice. 第一個呼叫會同步執行且成功。The first call runs synchronously and succeeds. 但是第二個呼叫, 因為它會線上程集區執行緒上以非同步方式執行, 所以會嘗試從非 UI 執行緒更新 UI。But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. 這會導致InvalidOperationException例外狀況。This results in a InvalidOperationException exception.

WPF 和 UWP 應用程式WPF and UWP apps

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 應用程式中的例外狀況。The following version of the DoSomeWork method eliminates the exception in a WPF app.

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 應用程式中的例外狀況。The following version of the DoSomeWork method eliminates the exception in a UWP app.

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

    // Report completion.
    bool uiAccess = textBox1.Dispatcher.HasThreadAccess;
    String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
                               milliseconds, uiAccess ? String.Empty : "non-");
    if (uiAccess)
        textBox1.Text += msg;
    else
        await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
    ' Simulate work.
    Await Task.Delay(milliseconds)

    ' Report completion.
    Dim uiAccess As Boolean = textBox1.Dispatcher.HasThreadAccess
    Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
                                      milliseconds, If(uiAccess, String.Empty, "non-"))
    If (uiAccess) Then
        textBox1.Text += msg
    Else
        Await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() textBox1.Text += msg)
    End If
End Sub

Windows Forms 應用程式Windows Forms apps

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

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

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

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

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

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

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

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

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

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

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

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

下列版本DoSomeWork的方法會消除 Windows Forms 應用程式中的例外狀況。The following version of the DoSomeWork method eliminates the exception in a Windows Forms app.

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

在反覆運算時變更集合Changing a collection while iterating it

Visual Basic foreach中的C#語句For Each或語句會用來逐一查看集合的成員, 並讀取或修改其個別元素。The foreach statement in C# or For Each statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. 不過, 它不能用來新增或移除集合中的專案。However, it can't be used to add or remove items from the collection. 這麼做會擲回例外狀況,其中包含類似的訊息:「集合已修改;InvalidOperationException 列舉運算可能無法執行。Doing this throws an InvalidOperationException exception with a message that is similar to, "Collection was modified; enumeration operation may not execute."

下列範例會逐一查看整數的集合, 以嘗試將每個整數的平方新增至集合。The following example iterates a collection of integers attempts to add the square of each integer to the collection. 此範例InvalidOperationException會在第一次呼叫List<T>.Add方法時擲回。The example throws an InvalidOperationException with the first call to the List<T>.Add method.

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

視您的應用程式邏輯而定, 您可以透過下列兩種方式的其中一種來排除例外狀況:You can eliminate the exception in one of two ways, depending on your application logic:

  • 如果必須在反覆運算時將元素加入至集合, 您可以使用for語句foreach (而不是或For Each) 逐一查看專案。If elements must be added to the collection while iterating it, you can iterate it by index using the for statement instead of foreach or For Each. 下列範例會使用 for 語句, 將集合中數位的平方新增至集合。The following example uses the for statement to add the square of numbers in the collection to the collection.

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

    請注意, 您必須先建立反復專案的數目, 方法是使用迴圈內的計數器來適當地結束迴圈, 方法是從Count -1 到0逐一反覆運算, 或在範例中藉由指派數位陣列中的元素與變數, 並使用它來建立迴圈的上限。Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropriately, by iterating backward, from Count - 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. 否則, 如果專案在每次反覆運算時新增至集合, 就會產生無止盡的迴圈結果。Otherwise, if an element is added to the collection on every iteration, an endless loop results.

  • 如果在反覆運算時不需要將專案新增至集合, 您可以將專案加入至您在逐一查看集合完成時加入的暫存集合中。If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. 下列範例會使用這種方法, 將集合中的數位平方加入至暫存集合, 然後將集合結合成單一陣列物件。The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object.

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

排序無法比較其物件的陣列或集合Sorting an array or collection whose objects cannot be compared

一般用途的排序方法 ( Array.Sort(Array)例如方法List<T>.Sort()或方法) 通常需要將至少一個物件IComparable排序, 才能執行IComparable<T>或介面。General-purpose sorting methods, such as the Array.Sort(Array) method or the List<T>.Sort() method, usually require that at least one of the objects to be sorted implement the IComparable<T> or the IComparable interface. 如果不是, 則無法排序集合或陣列, 而且方法InvalidOperationException會擲回例外狀況。If not, the collection or array cannot be sorted, and the method throws an InvalidOperationException exception. 下列範例會定義Person類別、在泛型List<T>物件Person中儲存兩個物件, 並嘗試排序它們。The following example defines a Person class, stores two Person objects in a generic List<T> object, and attempts to sort them. 如範例的輸出所示, 對List<T>.Sort()方法InvalidOperationException的呼叫會擲回。As the output from the example shows, the call to the List<T>.Sort() method throws an 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()
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()

您可以透過下列三種方式的其中一種來排除例外狀況:You can eliminate the exception in any of three ways:

  • 如果您可以擁有您想要排序的類型 (也就是, 如果您控制其原始程式碼), 您可以修改它來執行IComparable<T> IComparable或介面。If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the IComparable<T> or the IComparable interface. 這需要您執行IComparable<T>.CompareTo CompareTo或方法。This requires that you implement either the IComparable<T>.CompareTo or the CompareTo method. 將介面執行加入現有的類型並不是一種中斷變更。Adding an interface implementation to an existing type is not a breaking change.

    下列範例會使用這個方法來提供IComparable<T> Person類別的執行。The following example uses this approach to provide an IComparable<T> implementation for the Person class. 您仍然可以呼叫集合或陣列的一般排序方法, 如範例的輸出所示, 集合會成功排序。You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully.

    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}", LastName, 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
    
    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}", LastName, 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>執行介面的特殊用途排序類別。If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the IComparer<T> interface. 您可以呼叫Sort IComparer<T>包含參數之方法的多載。You can call an overload of the Sort method that includes an IComparer<T> parameter. 如果您想要開發可根據多個準則排序物件的特殊排序類別, 這種方法特別有用。This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria.

    下列範例會藉由開發用來排序PersonComparer Person集合的自訂類別來使用方法。The following example uses the approach by developing a custom PersonComparer class that is used to sort Person collections. 然後將這個類別的實例傳遞給List<T>.Sort(IComparer<T>)方法。It then passes an instance of this class to the List<T>.Sort(IComparer<T>) method.

    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
    
    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>委派來執行排序。If you cannot modify the source code for the type you are trying to sort, you can create a Comparison<T> delegate to perform the sorting. 委派簽章為The delegate signature is

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

    下列範例會藉由定義PersonComparison Comparison<T>符合委派簽章的方法來使用方法。The following example uses the approach by defining a PersonComparison method that matches the Comparison<T> delegate signature. 然後, 它會將此委派List<T>.Sort(Comparison<T>)傳遞給方法。It then passes this delegate to the List<T>.Sort(Comparison<T>) method.

    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
    
    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 >, 轉換為其基礎類型<Casting a Nullable<T> that is null to its underlying type

嘗試將的Nullable<T>值轉換InvalidOperationException為其null基礎類型時, 會擲回例外狀況並顯示錯誤訊息: 「可為 null 的物件必須有值。Attempting to cast a Nullable<T> value that is null to its underlying type throws an InvalidOperationException exception and displays the error message, "Nullable object must have a value.

下列範例InvalidOperationException會在嘗試反復執行Nullable(Of Integer)包含值的陣列時擲回例外狀況。The following example throws an InvalidOperationException exception when it attempts to iterate an array that includes a Nullable(Of Integer) value.

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

若要避免此例外狀況:To prevent the exception:

下列範例會執行這兩個動作InvalidOperationException來避免發生例外狀況。The following example does both to avoid the InvalidOperationException exception.

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
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.object 方法Calling a System.Linq.Enumerable method on an empty collection

Enumerable.Aggregate、 、、Enumerable.First 、、、Enumerable.SingleOrDefault和方法會在序列上執行作業, 並傳回單一結果。 Enumerable.Max Enumerable.Last Enumerable.Average Enumerable.Min Enumerable.SingleThe Enumerable.Aggregate, Enumerable.Average, Enumerable.First, Enumerable.Last, Enumerable.Max, Enumerable.Min, Enumerable.Single, and Enumerable.SingleOrDefault methods perform operations on a sequence and return a single result. 當序列是空的, 而InvalidOperationException其他多載傳回時, 這些方法的某些多null載會擲回例外狀況。Some overloads of these methods throw an InvalidOperationException exception when the sequence is empty, while other overloads return null. Enumerable.SingleOrDefault序列包含一個以上InvalidOperationException的元素時, 此方法也會擲回例外狀況。The Enumerable.SingleOrDefault method also throws an InvalidOperationException exception when the sequence contains more than one element.

注意

InvalidOperationException回例外狀況的大部分方法都是多載。Most of the methods that throw an InvalidOperationException exception are overloads. 請確定您瞭解您所選擇之多載的行為。Be sure that you understand the behavior of the overload that you choose.

下表列出來自呼叫某些InvalidOperationException System.Linq.Enumerable方法所擲回之例外狀況物件的例外狀況訊息。The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to some System.Linq.Enumerable methods.

方法Method 訊息Message
Aggregate
Average
Last
Max
Min
序列未包含任何元素Sequence contains no elements
First 序列未包含相符的元素Sequence contains no matching element
Single
SingleOrDefault
序列包含一個以上相符的元素Sequence contains more than one matching element

排除或處理例外狀況的方式, 取決於您的應用程式假設, 以及您所呼叫的特定方法。How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call.

這些範例會提供額外的詳細資料。The examples provide additional detail.

下列範例會使用Enumerable.Average方法來計算值大於4之序列的平均值。The following example uses the Enumerable.Average method to compute the average of a sequence whose values are greater than 4. 由於原始陣列中沒有任何值超過 4, 因此序列中不會包含任何值, 而且方法InvalidOperationException會擲回例外狀況。Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an InvalidOperationException exception.

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()
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方法來判斷序列是否包含任何專案, 然後再呼叫處理序列的方法, 即可排除例外狀況, 如下列範例所示。The exception can be eliminated by calling the Any method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows.

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.
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方法會傳回序列中的第一個專案, 或序列中符合指定之條件的第一個元素。The Enumerable.First method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. 如果序列是空的, 因此沒有第一個元素, 則InvalidOperationException會擲回例外狀況。If the sequence is empty and therefore does not have a first element, it throws an InvalidOperationException exception.

在下列範例中, Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)方法InvalidOperationException會擲回例外狀況, 因為 dbQueryResults 陣列未包含大於4的元素。In the following example, the Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method throws an InvalidOperationException exception because the dbQueryResults array doesn't contain an element greater than 4.

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()
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而不是, 以傳回指定或預設值。You can call the Enumerable.FirstOrDefault method instead of Enumerable.First to return a specified or default value. 如果方法找不到序列中的第一個元素, 則會傳回該資料類型的預設值。If the method does not find a first element in the sequence, it returns the default value for that data type. 預設值null適用于參考型別, 數值資料類型為零, 而DateTime.MinValue DateTime類型為。The default value is null for a reference type, zero for a numeric data type, and DateTime.MinValue for the DateTime type.

注意

解讀Enumerable.FirstOrDefault方法所傳回的值通常是複雜的, 因為該類型的預設值可以是序列中的有效值。Interpreting the value returned by the Enumerable.FirstOrDefault method is often complicated by the fact that the default value of the type can be a valid value in the sequence. 在此情況下, 您會呼叫Enumerable.Any方法, 以判斷序列是否具有有效的成員, 然後Enumerable.First再呼叫方法。In this case, you an call the Enumerable.Any method to determine whether the sequence has valid members before calling the Enumerable.First method.

下列範例會呼叫Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>)方法, 以避免在上一個範例中擲回的InvalidOperationException例外狀況。The following example calls the Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method to prevent the InvalidOperationException exception thrown in the previous example.

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.
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.

在沒有一個元素的序列上呼叫可列舉的 SingleOrDefault。Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element

Enumerable.Single方法會傳回序列的唯一元素, 或符合指定條件之序列的唯一元素。The Enumerable.Single method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. 如果序列中沒有任何元素, 或如果有多個專案, 方法InvalidOperationException就會擲回例外狀況。If there are no elements in the sequence, or if there is more than one element , the method throws an InvalidOperationException exception.

當序列中沒有Enumerable.SingleOrDefault包含任何元素時, 您可以使用方法來傳回預設值, 而不是擲回例外狀況。You can use the Enumerable.SingleOrDefault method to return a default value instead of throwing an exception when the sequence contains no elements. 不過, 當Enumerable.SingleOrDefault序列包含一個以上InvalidOperationException的元素時, 方法仍會擲回例外狀況。However, the Enumerable.SingleOrDefault method still throws an InvalidOperationException exception when the sequence contains more than one element.

下表列出來自InvalidOperationException Enumerable.SingleEnumerable.SingleOrDefault方法的呼叫所擲回之例外狀況物件的例外狀況訊息。The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to the Enumerable.Single and Enumerable.SingleOrDefault methods.

方法Method 訊息Message
Single 序列未包含相符的元素Sequence contains no matching element
Single
SingleOrDefault
序列包含一個以上相符的元素Sequence contains more than one matching element

在下列範例中, Enumerable.Single方法InvalidOperationException的呼叫會擲回例外狀況, 因為序列沒有大於4的元素。In the following example, the call to the Enumerable.Single method throws an InvalidOperationException exception because the sequence doesn't have an element greater than 4.

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()
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呼叫方法來擲回例外狀況。The following example attempts to prevent the InvalidOperationException exception thrown when a sequence is empty by instead calling the Enumerable.SingleOrDefault method. 不過, 由於此順序會傳回值大於2的多個元素, 因此也InvalidOperationException會擲回例外狀況。However, because this sequence returns multiple elements whose value is greater than 2, it also throws an InvalidOperationException exception.

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()
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呼叫方法會假設符合指定準則的序列或序列僅包含一個元素。Calling the Enumerable.Single method assumes that either a sequence or the sequence that meets specified criteria contains only one element. Enumerable.SingleOrDefault假設有零個或一個結果的序列, 但沒有其他。Enumerable.SingleOrDefault assumes a sequence with zero or one result, but no more. 如果此假設是您的第一項, 但不符合這些條件, 則會適當地重新擲回或InvalidOperationException捕捉產生的。If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting InvalidOperationException is appropriate. 否則, 或者, 如果您預期不正確條件會以某些頻率發生, 您應該考慮使用其他Enumerable方法, FirstOrDefault例如或WhereOtherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other Enumerable method, such as FirstOrDefault or Where.

動態跨應用程式域欄位存取Dynamic cross-application domain field access

如果包含您嘗試取得之位址的欄位不InvalidOperationException在您的程式碼執行所在的應用程式域中, Microsoft中繼語言(MSIL)指令會擲回例外狀況。OpCodes.LdfldaThe OpCodes.Ldflda Microsoft intermediate language (MSIL) instruction throws an InvalidOperationException exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. 只能從它所在的應用程式域存取欄位的位址。The address of a field can only be accessed from the application domain in which it resides.

擲回 InvalidOperationException 例外狀況Throwing an InvalidOperationException exception

只有當您的InvalidOperationException物件狀態因某些原因而不支援特定的方法呼叫時, 才會擲回例外狀況。You should throw an InvalidOperationException exception only when the state of your object for some reason does not support a particular method call. 也就是說, 方法呼叫在某些情況或內容中是有效的, 但在其他情況下則無效。That is, the method call is valid in some circumstances or contexts, but is invalid in others.

如果方法調用失敗是因為引數無效, 則ArgumentException應該改為擲回或其中一個衍生ArgumentOutOfRangeException ArgumentNullException類別。If the method invocation failure is due to invalid arguments, then ArgumentException or one of its derived classes, ArgumentNullException or ArgumentOutOfRangeException, should be thrown instead.

其他資訊Miscellaneous information

InvalidOperationException使用 HRESULT COR_E_INVALIDOPERATION, 其值為0x80131509。InvalidOperationException uses the HRESULT COR_E_INVALIDOPERATION, which has the value 0x80131509.

如需執行個體的初始屬性值的清單InvalidOperationException,請參閱InvalidOperationException建構函式。For a list of initial property values for an instance of InvalidOperationException, see the InvalidOperationException constructors.

建構函式

InvalidOperationException() InvalidOperationException() InvalidOperationException() InvalidOperationException()

初始化 InvalidOperationException 類別的新執行個體。Initializes a new instance of the InvalidOperationException class.

InvalidOperationException(SerializationInfo, StreamingContext) InvalidOperationException(SerializationInfo, StreamingContext) InvalidOperationException(SerializationInfo, StreamingContext) InvalidOperationException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 InvalidOperationException 類別的新執行個體。Initializes a new instance of the InvalidOperationException class with serialized data.

InvalidOperationException(String) InvalidOperationException(String) InvalidOperationException(String) InvalidOperationException(String)

使用指定的錯誤訊息,初始化 InvalidOperationException 類別的新執行個體。Initializes a new instance of the InvalidOperationException class with a specified error message.

InvalidOperationException(String, Exception) InvalidOperationException(String, Exception) InvalidOperationException(String, Exception) InvalidOperationException(String, Exception)

使用指定的錯誤訊息以及造成此例外狀況的內部例外狀況的參考,初始化 InvalidOperationException 類別的新執行個體。Initializes a new instance of the InvalidOperationException class with a specified error message and a reference to the inner exception that is the cause of this exception.

屬性

Data Data Data Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

取得描述目前例外狀況的訊息。Gets a message that describes the current exception.

(Inherited from Exception)
Source Source Source Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(Inherited from Exception)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType() GetType() GetType() GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

建立並傳回目前例外狀況的字串表示。Creates and returns a string representation of the current exception.

(Inherited from Exception)

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

適用於

另請參閱