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:

重要

因為InvalidOperationException擲回例外狀況中各種不同的情況下,務必要讀取所傳回的例外狀況訊息Message屬性。Because 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>是 null,為其基礎類型 Casting a Nullable<T> that is null to its underlying type
在空集合上呼叫的 System.Linq.Enumerable 方法Calling a System.Linq.Enumerable method on an empty collection
在沒有一個項目序列呼叫 Enumerable.Single 或 Enumerable.SingleOrDefaultCalling 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. 大部分的 GUI (圖形化使用者介面) 應用程式架構,適用於.NET Framework,例如 Windows Form 和 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). InvalidOperationException當您嘗試從非 UI 執行緒的執行緒存取 UI 元素時擲回。An 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. 它會傳回true如果 UI 執行緒上執行的方法和false否則。It returns true if the method is running on the UI thread and false otherwise. 呼叫其中一個多載Dispatcher.InvokeUI 執行緒上排定呼叫的方法。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:

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

  • 按鈕控制項,名為threadExampleBtnA 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

foreach C# 中的陳述式或For EachVisual Basic 中的陳述式用來逐一查看集合的成員以及讀取或修改其個別項目。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陳述式來取代foreachFor EachIf 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. 下列範例會使用陳述式才會加入至集合的集合中的數字的平方。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<T>IComparable介面。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類別,就會有兩個存放區Person物件,在泛型List<T>物件,並嘗試加以排序。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()方法會擲回InvalidOperationExceptionAs 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>.CompareToCompareTo方法。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 > 是 null,為其基礎類型Casting a Nullable<T> that is null to its underlying type

嘗試轉型Nullable<T>值,亦即null為其基礎類型會擲回InvalidOperationException例外狀況,並顯示錯誤訊息: 「可為 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.Linq.Enumerable 方法Calling a System.Linq.Enumerable method on an empty collection

Enumerable.AggregateEnumerable.AverageEnumerable.FirstEnumerable.LastEnumerable.MaxEnumerable.MinEnumerable.Single,以及Enumerable.SingleOrDefault方法執行一連串作業,並傳回單一結果。The 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例外狀況時,序列是空的而其他多載會傳回nullSome 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.MinValueDateTime型別。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.

在沒有一個項目序列呼叫 Enumerable.Single 或 Enumerable.SingleOrDefaultCalling 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方法,例如FirstOrDefaultWhereOtherwise, 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

OpCodes.Ldflda Microsoft intermediate language (MSIL) 指令則會擲回InvalidOperationException如果包含想要擷取其地址 欄位的物件不在您的程式碼執行所在的應用程式定義域內的例外狀況。The 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或其衍生的類別,其中ArgumentNullExceptionArgumentOutOfRangeException,應該改為擲回。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)

適用於

另請參閱