System.InvalidOperationException, klasa

Ten artykuł zawiera dodatkowe uwagi dotyczące dokumentacji referencyjnej dla tego interfejsu API.

InvalidOperationException jest używany w przypadkach, gdy niepowodzenie wywołania metody jest spowodowane przyczynami innymi niż nieprawidłowe argumenty. Zazwyczaj jest zgłaszany, gdy stan obiektu nie może obsługiwać wywołania metody. Na przykład wyjątek InvalidOperationException jest zgłaszany przez metody, takie jak:

  • IEnumerator.MoveNext jeśli obiekty kolekcji są modyfikowane po utworzeniu modułu wyliczającego. Aby uzyskać więcej informacji, zobacz Zmienianie kolekcji podczas iteracji.
  • ResourceSet.GetString jeśli zestaw zasobów zostanie zamknięty przed wywołaniem metody.
  • XContainer.Add, jeśli obiekt lub obiekty do dodania spowoduje niepoprawnie ustrukturyzowany dokument XML.
  • Metoda, która próbuje manipulować interfejsem użytkownika z wątku, który nie jest głównym wątkiem ani wątkiem interfejsu użytkownika.

Ważne

InvalidOperationException Ponieważ wyjątek można zgłosić w wielu różnych okolicznościach, ważne jest, aby odczytać komunikat o wyjątku zwrócony Message przez właściwość .

InvalidOperationException używa wartości HRESULT COR_E_INVALIDOPERATION, która ma wartość 0x80131509.

Aby uzyskać listę początkowych wartości właściwości dla wystąpienia InvalidOperationExceptionprogramu , zobacz InvalidOperationException konstruktory.

Typowe przyczyny wyjątków InvalidOperationException

W poniższych sekcjach pokazano, jak niektóre typowe przypadki, w których wyjątek InvalidOperationException jest zgłaszany w aplikacji. Sposób obsługi problemu zależy od konkretnej sytuacji. Najczęściej jednak wyjątek wynika z błędu dewelopera, a InvalidOperationException wyjątek można przewidzieć i uniknąć.

Aktualizowanie wątku interfejsu użytkownika z wątku innego niż interfejs użytkownika

Często wątki procesów roboczych służą do wykonywania niektórych zadań w tle, które obejmują zbieranie danych do wyświetlania w interfejsie użytkownika aplikacji. Jednak. większość struktur aplikacji gui (graficznego interfejsu użytkownika) dla platformy .NET, takich jak Windows Forms i Windows Presentation Foundation (WPF), umożliwiają dostęp do obiektów graficznego interfejsu użytkownika tylko z wątku, który tworzy interfejs użytkownika i zarządza nim (wątek główny lub interfejs użytkownika). Element InvalidOperationException jest zgłaszany podczas próby uzyskania dostępu do elementu interfejsu użytkownika z wątku innego niż wątek interfejsu użytkownika. Tekst komunikatu o wyjątku jest wyświetlany w poniższej tabeli.

Typ aplikacji Komunikat
Aplikacja WPF Wątek wywołujący nie może uzyskać dostępu do tego obiektu, ponieważ jest on właścicielem innego wątku.
Aplikacja platformy UNIWERSALNEJ systemu Windows Aplikacja nosi nazwę interfejsu, który został marshaled dla innego wątku.
Aplikacja Windows Forms Nieprawidłowa operacja między wątkami: Kontrolka "TextBox1" uzyskiwana z wątku innego niż wątek, na który został utworzony.

Struktury interfejsu użytkownika dla platformy .NET implementują wzorzec dyspozytora , który zawiera metodę sprawdzania, czy wywołanie elementu interfejsu użytkownika jest wykonywane w wątku interfejsu użytkownika i inne metody planowania wywołania wątku interfejsu użytkownika:

  • W aplikacjach WPF wywołaj metodę Dispatcher.CheckAccess , aby określić, czy metoda jest uruchomiona w wątku bez interfejsu użytkownika. Zwraca true wartość , jeśli metoda jest uruchomiona w wątku interfejsu użytkownika i false w przeciwnym razie. Wywołaj jedno z przeciążeń metody, Dispatcher.Invoke aby zaplanować wywołanie wątku interfejsu użytkownika.
  • W aplikacjach platformy UWP sprawdź CoreDispatcher.HasThreadAccess właściwość, aby określić, czy metoda jest uruchomiona w wątku bez interfejsu użytkownika. Wywołaj metodę , CoreDispatcher.RunAsync aby wykonać delegata, który aktualizuje wątek interfejsu użytkownika.
  • W aplikacjach Windows Forms użyj Control.InvokeRequired właściwości , aby określić, czy metoda jest uruchomiona w wątku bez interfejsu użytkownika. Wywołaj jedno z przeciążeń metody , Control.Invoke aby wykonać delegata, który aktualizuje wątek interfejsu użytkownika.

W poniższych przykładach pokazano InvalidOperationException wyjątek zgłaszany podczas próby zaktualizowania elementu interfejsu użytkownika z wątku innego niż wątek, który go utworzył. Każdy przykład wymaga utworzenia dwóch kontrolek:

  • Kontrolka pola tekstowego o nazwie textBox1. W aplikacji Windows Forms należy ustawić jej Multiline właściwość na true.
  • Kontrolka przycisku o nazwie threadExampleBtn. W przykładzie przedstawiono procedurę obsługi dla ThreadsExampleBtn_Clickzdarzenia przycisku Click .

W każdym przypadku threadExampleBtn_Click program obsługi zdarzeń wywołuje metodę DoSomeWork dwa razy. Pierwsze wywołanie jest uruchamiane synchronicznie i kończy się pomyślnie. Jednak drugie wywołanie, ponieważ jest uruchamiane asynchronicznie w wątku puli wątków, próbuje zaktualizować interfejs użytkownika z wątku innego niż interfejs użytkownika. Spowoduje to wyjątek InvalidOperationException .

Aplikacje WPF

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

    textBox1.Text = "Simulating work on UI thread.\n";
    DoSomeWork(20);
    textBox1.Text += "Work completed...\n";

    textBox1.Text += "Simulating work on non-UI thread.\n";
    await Task.Run(() => DoSomeWork(1000));
    textBox1.Text += "Work completed...\n";
}

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

    // Report completion.
    var msg = String.Format("Some work completed in {0} ms.\n", milliseconds);
    textBox1.Text += msg;
}

Poniższa wersja DoSomeWork metody eliminuje wyjątek w aplikacji WPF.

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

    // Report completion.
    bool uiAccess = textBox1.Dispatcher.CheckAccess();
    String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
                               milliseconds, uiAccess ? String.Empty : "non-");
    if (uiAccess)
        textBox1.Text += msg;
    else
        textBox1.Dispatcher.Invoke(() => { textBox1.Text += msg; });
}

Aplikacja Windows Forms

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

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

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

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

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

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

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

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

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

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

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

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

Poniższa wersja DoSomeWork metody eliminuje wyjątek w aplikacji Windows Forms.

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

    // Report completion.
    bool uiMarshal = textBox1.InvokeRequired;
    String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
                               milliseconds, uiMarshal ? String.Empty : "non-");
    lines.Add(msg);

    if (uiMarshal) {
        textBox1.Invoke(new Action(() => { textBox1.Lines = lines.ToArray(); }));
    }
    else {
        textBox1.Lines = lines.ToArray();
    }
}
Private Async Sub DoSomeWork(milliseconds As Integer)
    ' Simulate work.
    Await Task.Delay(milliseconds)

    ' Report completion.
    Dim uiMarshal As Boolean = TextBox1.InvokeRequired
    Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
                                      milliseconds, If(uiMarshal, String.Empty, "non-"))
    lines.Add(msg)

    If uiMarshal Then
        TextBox1.Invoke(New Action(Sub() TextBox1.Lines = lines.ToArray()))
    Else
        TextBox1.Lines = lines.ToArray()
    End If
End Sub

Zmiana kolekcji podczas iteracji

Instrukcja foreach w języku C#, for...in w języku F# lub For Each instrukcja w języku Visual Basic służy do iterowania elementów członkowskich kolekcji oraz odczytywania lub modyfikowania poszczególnych elementów. Nie można jednak jej użyć do dodawania ani usuwania elementów z kolekcji. Spowoduje to zgłoszenie InvalidOperationException wyjątku z komunikatem podobnym do następującego: "Kolekcja została zmodyfikowana; operacja wyliczania może nie zostać wykonana".

Poniższy przykład iteruje kolekcję liczb całkowitych, aby dodać kwadrat każdej liczby całkowitej do kolekcji. W przykładzie jest zgłaszane polecenie InvalidOperationException z pierwszym wywołaniem List<T>.Add metody .

using System;
using System.Collections.Generic;

public class IteratingEx1
{
    public static void Main()
    {
        var numbers = new List<int>() { 1, 2, 3, 4, 5 };
        foreach (var number in numbers)
        {
            int square = (int)Math.Pow(number, 2);
            Console.WriteLine("{0}^{1}", number, square);
            Console.WriteLine("Adding {0} to the collection...\n", square);
            numbers.Add(square);
        }
    }
}
// The example displays the following output:
//    1^1
//    Adding 1 to the collection...
//
//
//    Unhandled Exception: System.InvalidOperationException: Collection was modified;
//       enumeration operation may not execute.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
//       at Example.Main()
open System

let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
for number in numbers do
    let square = Math.Pow(number, 2) |> int
    printfn $"{number}^{square}"
    printfn $"Adding {square} to the collection...\n"
    numbers.Add square

// The example displays the following output:
//    1^1
//    Adding 1 to the collection...
//
//
//    Unhandled Exception: System.InvalidOperationException: Collection was modified
//       enumeration operation may not execute.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
//       at <StartupCode$fs>.main()
Imports System.Collections.Generic

Module Example6
    Public Sub Main()
        Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
        For Each number In numbers
            Dim square As Integer = CInt(Math.Pow(number, 2))
            Console.WriteLine("{0}^{1}", number, square)
            Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
                           square)
            numbers.Add(square)
        Next
    End Sub
End Module
' The example displays the following output:
'    1^1
'    Adding 1 to the collection...
'    
'    
'    Unhandled Exception: System.InvalidOperationException: Collection was modified; 
'       enumeration operation may not execute.
'       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
'       at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
'       at Example.Main()

Wyjątek można wyeliminować na jeden z dwóch sposobów, w zależności od logiki aplikacji:

  • Jeśli elementy muszą zostać dodane do kolekcji podczas iteracji, można iterować ją za pomocą for instrukcji (for..to w języku F#) zamiast foreach, for...inlub For Each. W poniższym przykładzie użyto instrukcji for, aby dodać kwadrat liczb w kolekcji do kolekcji.

    using System;
    using System.Collections.Generic;
    
    public class IteratingEx2
    {
        public static void Main()
        {
            var numbers = new List<int>() { 1, 2, 3, 4, 5 };
    
            int upperBound = numbers.Count - 1;
            for (int ctr = 0; ctr <= upperBound; ctr++)
            {
                int square = (int)Math.Pow(numbers[ctr], 2);
                Console.WriteLine("{0}^{1}", numbers[ctr], square);
                Console.WriteLine("Adding {0} to the collection...\n", square);
                numbers.Add(square);
            }
    
            Console.WriteLine("Elements now in the collection: ");
            foreach (var number in numbers)
                Console.Write("{0}    ", number);
        }
    }
    // The example displays the following output:
    //    1^1
    //    Adding 1 to the collection...
    //
    //    2^4
    //    Adding 4 to the collection...
    //
    //    3^9
    //    Adding 9 to the collection...
    //
    //    4^16
    //    Adding 16 to the collection...
    //
    //    5^25
    //    Adding 25 to the collection...
    //
    //    Elements now in the collection:
    //    1    2    3    4    5    1    4    9    16    25
    
    open System
    open System.Collections.Generic
    
    let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
    
    let upperBound = numbers.Count - 1
    for i = 0 to upperBound do
        let square = Math.Pow(numbers[i], 2) |> int
        printfn $"{numbers[i]}^{square}"
        printfn $"Adding {square} to the collection...\n"
        numbers.Add square
    
    printfn "Elements now in the collection: "
    for number in numbers do
        printf $"{number}    "
    // The example displays the following output:
    //    1^1
    //    Adding 1 to the collection...
    //
    //    2^4
    //    Adding 4 to the collection...
    //
    //    3^9
    //    Adding 9 to the collection...
    //
    //    4^16
    //    Adding 16 to the collection...
    //
    //    5^25
    //    Adding 25 to the collection...
    //
    //    Elements now in the collection:
    //    1    2    3    4    5    1    4    9    16    25
    
    Imports System.Collections.Generic
    
    Module Example7
        Public Sub Main()
            Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
            Dim upperBound = numbers.Count - 1
    
            For ctr As Integer = 0 To upperBound
                Dim square As Integer = CInt(Math.Pow(numbers(ctr), 2))
                Console.WriteLine("{0}^{1}", numbers(ctr), square)
                Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
                               square)
                numbers.Add(square)
            Next
    
            Console.WriteLine("Elements now in the collection: ")
            For Each number In numbers
                Console.Write("{0}    ", number)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '    1^1
    '    Adding 1 to the collection...
    '    
    '    2^4
    '    Adding 4 to the collection...
    '    
    '    3^9
    '    Adding 9 to the collection...
    '    
    '    4^16
    '    Adding 16 to the collection...
    '    
    '    5^25
    '    Adding 25 to the collection...
    '    
    '    Elements now in the collection:
    '    1    2    3    4    5    1    4    9    16    25
    

    Należy pamiętać, że należy ustanowić liczbę iteracji przed iteracją kolekcji przy użyciu licznika wewnątrz pętli, który odpowiednio zakończy pętlę, iterując do tyłu, od Count - 1 do 0 lub, jak w przykładzie, przypisując liczbę elementów w tablicy do zmiennej i używając jej do ustalenia górnej granicy pętli. W przeciwnym razie, jeśli element zostanie dodany do kolekcji w każdej iteracji, wynik nieskończonej pętli.

  • Jeśli nie jest konieczne dodanie elementów do kolekcji podczas iteracji, możesz przechowywać elementy do dodania w kolekcji tymczasowej dodawanej po zakończeniu iteracji kolekcji. W poniższym przykładzie użyto tego podejścia, aby dodać kwadrat liczb w kolekcji do kolekcji tymczasowej, a następnie połączyć kolekcje w pojedynczy obiekt tablicy.

    using System;
    using System.Collections.Generic;
    
    public class IteratingEx3
    {
        public static void Main()
        {
            var numbers = new List<int>() { 1, 2, 3, 4, 5 };
            var temp = new List<int>();
    
            // Square each number and store it in a temporary collection.
            foreach (var number in numbers)
            {
                int square = (int)Math.Pow(number, 2);
                temp.Add(square);
            }
    
            // Combine the numbers into a single array.
            int[] combined = new int[numbers.Count + temp.Count];
            Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count);
            Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count);
    
            // Iterate the array.
            foreach (var value in combined)
                Console.Write("{0}    ", value);
        }
    }
    // The example displays the following output:
    //       1    2    3    4    5    1    4    9    16    25
    
    open System
    open System.Collections.Generic
    
    let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
    let temp = ResizeArray()
    
    // Square each number and store it in a temporary collection.
    for number in numbers do
        let square = Math.Pow(number, 2) |> int
        temp.Add square
    
    // Combine the numbers into a single array.
    let combined = Array.zeroCreate<int> (numbers.Count + temp.Count)
    Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count)
    Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count)
    
    // Iterate the array.
    for value in combined do
        printf $"{value}    "
    // The example displays the following output:
    //       1    2    3    4    5    1    4    9    16    25
    
    Imports System.Collections.Generic
    
    Module Example8
        Public Sub Main()
            Dim numbers As New List(Of Integer)({1, 2, 3, 4, 5})
            Dim temp As New List(Of Integer)()
    
            ' Square each number and store it in a temporary collection.
            For Each number In numbers
                Dim square As Integer = CInt(Math.Pow(number, 2))
                temp.Add(square)
            Next
    
            ' Combine the numbers into a single array.
            Dim combined(numbers.Count + temp.Count - 1) As Integer
            Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count)
            Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count)
    
            ' Iterate the array.
            For Each value In combined
                Console.Write("{0}    ", value)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       1    2    3    4    5    1    4    9    16    25
    

Sortowanie tablicy lub kolekcji, której nie można porównać obiektów

Metody sortowania ogólnego przeznaczenia, takie jak Array.Sort(Array) metoda lub List<T>.Sort() metoda, zwykle wymagają sortowania co najmniej jednego z obiektów implementujących IComparable<T> interfejs lub IComparable . W przeciwnym razie nie można sortować kolekcji lub tablicy, a metoda zgłasza InvalidOperationException wyjątek. Poniższy przykład definiuje klasę Person , przechowuje dwa Person obiekty w obiekcie ogólnym List<T> i próbuje je posortować. Jak pokazano w danych wyjściowych z przykładu, wywołanie List<T>.Sort() metody zgłasza błąd InvalidOperationException.

using System;
using System.Collections.Generic;

public class Person1
{
    public Person1(string fName, string lName)
    {
        FirstName = fName;
        LastName = lName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class ListSortEx1
{
    public static void Main()
    {
        var people = new List<Person1>();

        people.Add(new Person1("John", "Doe"));
        people.Add(new Person1("Jane", "Doe"));
        people.Sort();
        foreach (var person in people)
            Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
//       System.ArgumentException: At least one object must implement IComparable.
//       at System.Collections.Comparer.Compare(Object a, Object b)
//       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
//       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       --- End of inner exception stack trace ---
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
//       at Example.Main()
type Person(firstName: string, lastName: string) =
    member val FirstName = firstName with get, set
    member val LastName = lastName with get, set

let people = ResizeArray()

people.Add(Person("John", "Doe"))
people.Add(Person("Jane", "Doe"))
people.Sort()
for person in people do
    printfn $"{person.FirstName} {person.LastName}"
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
//       System.ArgumentException: At least one object must implement IComparable.
//       at System.Collections.Comparer.Compare(Object a, Object b)
//       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
//       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       --- End of inner exception stack trace ---
//       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
//       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
//       at <StartupCode$fs>.main()
Imports System.Collections.Generic

Public Class Person9
    Public Sub New(fName As String, lName As String)
        FirstName = fName
        LastName = lName
    End Sub

    Public Property FirstName As String
    Public Property LastName As String
End Class

Module Example9
    Public Sub Main()
        Dim people As New List(Of Person9)()

        people.Add(New Person9("John", "Doe"))
        people.Add(New Person9("Jane", "Doe"))
        people.Sort()
        For Each person In people
            Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
        Next
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. ---> 
'       System.ArgumentException: At least one object must implement IComparable.
'       at System.Collections.Comparer.Compare(Object a, Object b)
'       at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
'       at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
'       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
'       --- End of inner exception stack trace ---
'       at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
'       at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
'       at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
'       at Example.Main()

Wyjątek można wyeliminować na dowolny z trzech sposobów:

  • Jeśli możesz być właścicielem typu, który próbujesz sortować (czyli jeśli kontrolujesz jego kod źródłowy), możesz zmodyfikować go w celu zaimplementowania interfejsu IComparable<T>IComparable lub . Wymaga to zaimplementowania IComparable<T>.CompareTo metody lub CompareTo . Dodanie implementacji interfejsu do istniejącego typu nie jest zmianą powodującą niezgodność.

    W poniższym przykładzie użyto tego podejścia, aby zapewnić implementację IComparable<T> dla Person klasy . Nadal można wywołać ogólną metodę sortowania kolekcji lub tablicy, a dane wyjściowe z przykładu pokazują, że kolekcja zostanie posortowane pomyślnie.

    using System;
    using System.Collections.Generic;
    
    public class Person2 : IComparable<Person>
    {
        public Person2(String fName, String lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    
        public String FirstName { get; set; }
        public String LastName { get; set; }
    
        public int CompareTo(Person other)
        {
            return String.Format("{0} {1}", LastName, FirstName).
                   CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName));
        }
    }
    
    public class ListSortEx2
    {
        public static void Main()
        {
            var people = new List<Person2>();
    
            people.Add(new Person2("John", "Doe"));
            people.Add(new Person2("Jane", "Doe"));
            people.Sort();
            foreach (var person in people)
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
        }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    
    type Person(firstName: string, lastName: string) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
        
        interface IComparable<Person> with
            member this.CompareTo(other) =
                compare $"{this.LastName} {this.FirstName}" $"{other.LastName} {other.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(new Person("John", "Doe"))
    people.Add(new Person("Jane", "Doe"))
    people.Sort()
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person : Implements IComparable(Of Person)
       Public Sub New(fName As String, lName As String)
          FirstName = fName
          LastName = lName
       End Sub
       
       Public Property FirstName As String
       Public Property LastName As String
       
       Public Function CompareTo(other As Person) As Integer _
              Implements IComparable(Of Person).CompareTo
          Return String.Format("{0} {1}", LastName, FirstName).
                CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName))    
       End Function
    End Class
    
    Module Example10
        Public Sub Main()
            Dim people As New List(Of Person)()
    
            people.Add(New Person("John", "Doe"))
            people.Add(New Person("Jane", "Doe"))
            people.Sort()
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    
  • Jeśli nie możesz zmodyfikować kodu źródłowego dla typu, który próbujesz sortować, możesz zdefiniować klasę sortowania specjalnego przeznaczenia, która implementuje IComparer<T> interfejs. Można wywołać przeciążenie Sort metody zawierającej IComparer<T> parametr . Takie podejście jest szczególnie przydatne, jeśli chcesz opracować wyspecjalizowaną klasę sortowania, która może sortować obiekty na podstawie wielu kryteriów.

    W poniższym przykładzie użyto podejścia, tworząc klasę niestandardową PersonComparer używaną do sortowania Person kolekcji. Następnie przekazuje wystąpienie tej klasy do List<T>.Sort(IComparer<T>) metody .

    using System;
    using System.Collections.Generic;
    
    public class Person3
    {
        public Person3(String fName, String lName)
        {
            FirstName = fName;
            LastName = lName;
        }
    
        public String FirstName { get; set; }
        public String LastName { get; set; }
    }
    
    public class PersonComparer : IComparer<Person3>
    {
        public int Compare(Person3 x, Person3 y)
        {
            return String.Format("{0} {1}", x.LastName, x.FirstName).
                   CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName));
        }
    }
    
    public class ListSortEx3
    {
        public static void Main()
        {
            var people = new List<Person3>();
    
            people.Add(new Person3("John", "Doe"));
            people.Add(new Person3("Jane", "Doe"));
            people.Sort(new PersonComparer());
            foreach (var person in people)
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
        }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    open System.Collections.Generic
    
    type Person(firstName, lastName) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
    
    type PersonComparer() =
        interface IComparer<Person> with
            member _.Compare(x: Person, y: Person) =
                $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(Person("John", "Doe"))
    people.Add(Person("Jane", "Doe"))
    people.Sort(PersonComparer())
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person11
        Public Sub New(fName As String, lName As String)
            FirstName = fName
            LastName = lName
        End Sub
    
        Public Property FirstName As String
        Public Property LastName As String
    End Class
    
    Public Class PersonComparer : Implements IComparer(Of Person11)
        Public Function Compare(x As Person11, y As Person11) As Integer _
              Implements IComparer(Of Person11).Compare
            Return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName))
        End Function
    End Class
    
    Module Example11
        Public Sub Main()
            Dim people As New List(Of Person11)()
    
            people.Add(New Person11("John", "Doe"))
            people.Add(New Person11("Jane", "Doe"))
            people.Sort(New PersonComparer())
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    
  • Jeśli nie możesz zmodyfikować kodu źródłowego dla typu, który próbujesz sortować, możesz utworzyć Comparison<T> delegata w celu przeprowadzenia sortowania. Podpis delegata to

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

    W poniższym przykładzie użyto podejścia, definiując metodę zgodną PersonComparison z podpisem delegowanym Comparison<T> . Następnie przekazuje ten delegat do List<T>.Sort(Comparison<T>) metody .

    using System;
    using System.Collections.Generic;
    
    public class Person
    {
       public Person(String fName, String lName)
       {
          FirstName = fName;
          LastName = lName;
       }
    
       public String FirstName { get; set; }
       public String LastName { get; set; }
    }
    
    public class ListSortEx4
    {
       public static void Main()
       {
          var people = new List<Person>();
    
          people.Add(new Person("John", "Doe"));
          people.Add(new Person("Jane", "Doe"));
          people.Sort(PersonComparison);
          foreach (var person in people)
             Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
       }
    
       public static int PersonComparison(Person x, Person y)
       {
          return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName));
       }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    open System
    open System.Collections.Generic
    
    type Person(firstName, lastName) =
        member val FirstName = firstName with get, set
        member val LastName = lastName with get, set
    
    let personComparison (x: Person) (y: Person) =
        $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}"
    
    let people = ResizeArray()
    
    people.Add(Person("John", "Doe"))
    people.Add(Person("Jane", "Doe"))
    people.Sort personComparison
    for person in people do
        printfn $"{person.FirstName} {person.LastName}"
    
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
    Imports System.Collections.Generic
    
    Public Class Person12
        Public Sub New(fName As String, lName As String)
            FirstName = fName
            LastName = lName
        End Sub
    
        Public Property FirstName As String
        Public Property LastName As String
    End Class
    
    Module Example12
        Public Sub Main()
            Dim people As New List(Of Person12)()
    
            people.Add(New Person12("John", "Doe"))
            people.Add(New Person12("Jane", "Doe"))
            people.Sort(AddressOf PersonComparison)
            For Each person In people
                Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
            Next
        End Sub
    
        Public Function PersonComparison(x As Person12, y As Person12) As Integer
            Return String.Format("{0} {1}", x.LastName, x.FirstName).
                 CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName))
        End Function
    End Module
    ' The example displays the following output:
    '       Jane Doe
    '       John Doe
    

Rzutowanie wartości Nullable<T> , która ma wartość null do jego typu bazowego

Próba rzutowania wartości, która jest null jego typem bazowymNullable<T>, zgłasza InvalidOperationException wyjątek i wyświetla komunikat o błędzie "Obiekt dopuszczający wartość null musi mieć wartość.

Poniższy przykład zgłasza InvalidOperationException wyjątek podczas próby iteracji tablicy zawierającej Nullable(Of Integer) wartość.

using System;
using System.Linq;

public class NullableEx1
{
   public static void Main()
   {
      var queryResult = new int?[] { 1, 2, null, 4 };
      var map = queryResult.Select(nullableInt => (int)nullableInt);

      // Display list.
      foreach (var num in map)
         Console.Write("{0} ", num);
      Console.WriteLine();
   }
}
// The example displays the following output:
//    1 2
//    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at Example.<Main>b__0(Nullable`1 nullableInt)
//       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
//       at Example.Main()
open System
open System.Linq

let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let map = queryResult.Select(fun nullableInt -> nullableInt.Value)

// Display list.
for num in map do
    printf $"{num} "
printfn ""
// The example displays the following output:
//    1 2
//    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
//       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
//       at Example.<Main>b__0(Nullable`1 nullableInt)
//       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example13
    Public Sub Main()
        Dim queryResult = New Integer?() {1, 2, Nothing, 4}
        Dim map = queryResult.Select(Function(nullableInt) CInt(nullableInt))

        ' Display list.
        For Each num In map
            Console.Write("{0} ", num)
        Next
        Console.WriteLine()
    End Sub
End Module
' The example displays thIe following output:
'    1 2
'    Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
'       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
'       at Example.<Main>b__0(Nullable`1 nullableInt)
'       at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
'       at Example.Main()

Aby zapobiec wyjątkowi:

W poniższym przykładzie oba te czynności pozwalają uniknąć wyjątku InvalidOperationException .

using System;
using System.Linq;

public class NullableEx2
{
   public static void Main()
   {
      var queryResult = new int?[] { 1, 2, null, 4 };
      var numbers = queryResult.Select(nullableInt => (int)nullableInt.GetValueOrDefault());

      // Display list using Nullable<int>.HasValue.
      foreach (var number in numbers)
         Console.Write("{0} ", number);
      Console.WriteLine();

      numbers = queryResult.Select(nullableInt => (int) (nullableInt.HasValue ? nullableInt : -1));
      // Display list using Nullable<int>.GetValueOrDefault.
      foreach (var number in numbers)
         Console.Write("{0} ", number);
      Console.WriteLine();
   }
}
// The example displays the following output:
//       1 2 0 4
//       1 2 -1 4
open System
open System.Linq

let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let numbers = queryResult.Select(fun nullableInt -> nullableInt.GetValueOrDefault())

// Display list using Nullable<int>.HasValue.
for number in numbers do
    printf $"{number} "
printfn ""

let numbers2 = queryResult.Select(fun nullableInt -> if nullableInt.HasValue then nullableInt.Value else -1)
// Display list using Nullable<int>.GetValueOrDefault.
for number in numbers2 do
    printf $"{number} "
printfn ""
// The example displays the following output:
//       1 2 0 4
//       1 2 -1 4
Imports System.Linq

Module Example14
    Public Sub Main()
        Dim queryResult = New Integer?() {1, 2, Nothing, 4}
        Dim numbers = queryResult.Select(Function(nullableInt) _
                                          CInt(nullableInt.GetValueOrDefault()))
        ' Display list.
        For Each number In numbers
            Console.Write("{0} ", number)
        Next
        Console.WriteLine()

        ' Use -1 to indicate a missing values.
        numbers = queryResult.Select(Function(nullableInt) _
                                      CInt(If(nullableInt.HasValue, nullableInt, -1)))
        ' Display list.
        For Each number In numbers
            Console.Write("{0} ", number)
        Next
        Console.WriteLine()

    End Sub
End Module
' The example displays the following output:
'       1 2 0 4
'       1 2 -1 4

Wywoływanie metody System.Linq.Enumerable w pustej kolekcji

Metody Enumerable.Aggregate, Enumerable.Average, Enumerable.FirstEnumerable.MinEnumerable.SingleEnumerable.LastEnumerable.Maxi wykonują Enumerable.SingleOrDefault operacje na sekwencji i zwracają pojedynczy wynik. Niektóre przeciążenia tych metod zgłaszają InvalidOperationException wyjątek, gdy sekwencja jest pusta, podczas gdy inne przeciążenia zwracają wartość null. Metoda Enumerable.SingleOrDefault zgłasza InvalidOperationException również wyjątek, gdy sekwencja zawiera więcej niż jeden element.

Uwaga

Większość metod zgłaszających InvalidOperationException wyjątek to przeciążenia. Upewnij się, że rozumiesz zachowanie wybranego przeciążenia.

W poniższej tabeli wymieniono komunikaty wyjątków z InvalidOperationException obiektów wyjątków zgłaszanych przez wywołania do niektórych System.Linq.Enumerable metod.

Method Komunikat
Aggregate
Average
Last
Max
Min
Sekwencja nie zawiera żadnych elementów
First Sekwencja nie zawiera pasującego elementu
Single
SingleOrDefault
Sekwencja zawiera więcej niż jeden pasujący element

Sposób wyeliminowania wyjątku lub jego obsługi zależy od założeń aplikacji i od określonej metody, którą wywołujesz.

  • Jeśli celowo wywołasz jedną z tych metod bez sprawdzania pustej sekwencji, zakładasz, że sekwencja nie jest pusta i że pusta sekwencja jest nieoczekiwanym wystąpieniem. W takim przypadku przechwytywanie lub ponowne wychwycenie wyjątku jest odpowiednie.

  • Jeśli niepowodzenie sprawdzania pustej sekwencji było niezamierzone, możesz wywołać jedno z przeciążeń przeciążenia Enumerable.Any , aby określić, czy sekwencja zawiera jakiekolwiek elementy.

    Napiwek

    Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) Wywołanie metody przed wygenerowaniem sekwencji może zwiększyć wydajność, jeśli dane do przetworzenia mogą zawierać dużą liczbę elementów lub jeśli operacja, która generuje sekwencję, jest kosztowna.

  • Jeśli wywołaliśmy metodę, taką jak Enumerable.First, Enumerable.Lastlub Enumerable.Single, możesz zastąpić alternatywną metodę, taką jak Enumerable.FirstOrDefault, Enumerable.LastOrDefaultlub Enumerable.SingleOrDefault, zwracającą wartość domyślną zamiast elementu członkowskiego sekwencji.

Przykłady zawierają dodatkowe szczegóły.

W poniższym przykładzie użyto Enumerable.Average metody do obliczenia średniej sekwencji, której wartości są większe niż 4. Ponieważ żadna wartość z oryginalnej tablicy nie przekracza 4, żadne wartości nie są uwzględniane w sekwencji, a metoda zgłasza InvalidOperationException wyjątek.

using System;
using System.Linq;

public class Example
{
   public static void Main()
   {
      int[] data = { 1, 2, 3, 4 };
      var average = data.Where(num => num > 4).Average();
      Console.Write("The average of numbers greater than 4 is {0}",
                    average);
   }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
//       at System.Linq.Enumerable.Average(IEnumerable`1 source)
//       at Example.Main()
open System
open System.Linq

let data = [| 1; 2; 3; 4 |]
let average = 
   data.Where(fun num -> num > 4).Average();
printfn $"The average of numbers greater than 4 is {average}"
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
//       at System.Linq.Enumerable.Average(IEnumerable`1 source)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example
   Public Sub Main()
      Dim data() As Integer = { 1, 2, 3, 4 }
      Dim average = data.Where(Function(num) num > 4).Average()
      Console.Write("The average of numbers greater than 4 is {0}",
                    average)
   End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
'       at System.Linq.Enumerable.Average(IEnumerable`1 source)
'       at Example.Main()

Wyjątek można wyeliminować przez wywołanie Any metody w celu określenia, czy sekwencja zawiera jakiekolwiek elementy przed wywołaniem metody, która przetwarza sekwencję, jak pokazano w poniższym przykładzie.

using System;
using System.Linq;

public class EnumerableEx2
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };
        var moreThan4 = dbQueryResults.Where(num => num > 4);

        if (moreThan4.Any())
            Console.WriteLine("Average value of numbers greater than 4: {0}:",
                              moreThan4.Average());
        else
            // handle empty collection
            Console.WriteLine("The dataset has no values greater than 4.");
    }
}
// The example displays the following output:
//       The dataset has no values greater than 4.
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]
let moreThan4 = 
    dbQueryResults.Where(fun num -> num > 4)

if moreThan4.Any() then
    printfn $"Average value of numbers greater than 4: {moreThan4.Average()}:"
else
    // handle empty collection
    printfn "The dataset has no values greater than 4."

// The example displays the following output:
//       The dataset has no values greater than 4.
Imports System.Linq

Module Example1
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}
        Dim moreThan4 = dbQueryResults.Where(Function(num) num > 4)

        If moreThan4.Any() Then
            Console.WriteLine("Average value of numbers greater than 4: {0}:",
                             moreThan4.Average())
        Else
            ' Handle empty collection. 
            Console.WriteLine("The dataset has no values greater than 4.")
        End If
    End Sub
End Module
' The example displays the following output:
'       The dataset has no values greater than 4.

Metoda Enumerable.First zwraca pierwszy element w sekwencji lub pierwszy element w sekwencji, która spełnia określony warunek. Jeśli sekwencja jest pusta i dlatego nie ma pierwszego elementu, zgłasza wyjątek InvalidOperationException .

W poniższym przykładzie metoda zgłasza InvalidOperationException wyjątek, Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) ponieważ tablica dbQueryResults nie zawiera elementu większego niż 4.

using System;
using System.Linq;

public class EnumerableEx3
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var firstNum = dbQueryResults.First(n => n > 4);

        Console.WriteLine("The first value greater than 4 is {0}",
                          firstNum);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let firstNum = dbQueryResults.First(fun n -> n > 4)

printfn $"The first value greater than 4 is {firstNum}"

// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example2
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim firstNum = dbQueryResults.First(Function(n) n > 4)

        Console.WriteLine("The first value greater than 4 is {0}",
                        firstNum)
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains no matching element
'       at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

Można wywołać metodę Enumerable.FirstOrDefault zamiast Enumerable.First zwracać określoną lub domyślną wartość. Jeśli metoda nie znajdzie pierwszego elementu w sekwencji, zwraca wartość domyślną dla tego typu danych. Wartością domyślną jest null typ odwołania, zero dla typu danych liczbowych i DateTime.MinValue dla DateTime typu.

Uwaga

Interpretowanie wartości zwracanej przez Enumerable.FirstOrDefault metodę jest często skomplikowane przez fakt, że domyślna wartość typu może być prawidłową wartością w sekwencji. W takim przypadku wywołasz metodę Enumerable.Any , aby określić, czy sekwencja ma prawidłowe elementy członkowskie przed wywołaniem Enumerable.First metody .

Poniższy przykład wywołuje metodę Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) , aby zapobiec wystąpieniu wyjątku InvalidOperationException w poprzednim przykładzie.

using System;
using System.Linq;

public class EnumerableEx4
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var firstNum = dbQueryResults.FirstOrDefault(n => n > 4);

        if (firstNum == 0)
            Console.WriteLine("No value is greater than 4.");
        else
            Console.WriteLine("The first value greater than 4 is {0}",
                              firstNum);
    }
}
// The example displays the following output:
//       No value is greater than 4.
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let firstNum = dbQueryResults.FirstOrDefault(fun n -> n > 4)

if firstNum = 0 then
    printfn "No value is greater than 4."
else
    printfn $"The first value greater than 4 is {firstNum}"

// The example displays the following output:
//       No value is greater than 4.
Imports System.Linq

Module Example3
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim firstNum = dbQueryResults.FirstOrDefault(Function(n) n > 4)

        If firstNum = 0 Then
            Console.WriteLine("No value is greater than 4.")
        Else
            Console.WriteLine("The first value greater than 4 is {0}",
                           firstNum)
        End If
    End Sub
End Module
' The example displays the following output:
'       No value is greater than 4.

Wywołaj metodę Enumerable.Single lub Enumerable.SingleOrDefault w sekwencji bez jednego elementu

Metoda Enumerable.Single zwraca jedyny element sekwencji lub jedyny element sekwencji, który spełnia określony warunek. Jeśli nie ma żadnych elementów w sekwencji lub jeśli istnieje więcej niż jeden element, metoda zgłasza InvalidOperationException wyjątek.

Możesz użyć Enumerable.SingleOrDefault metody , aby zwrócić wartość domyślną zamiast zgłaszać wyjątek, gdy sekwencja nie zawiera żadnych elementów. Jednak metoda nadal zgłasza InvalidOperationException wyjątek, Enumerable.SingleOrDefault gdy sekwencja zawiera więcej niż jeden element.

W poniższej tabeli wymieniono komunikaty wyjątków z InvalidOperationException obiektów wyjątków zgłaszanych przez wywołania Enumerable.Single metod i Enumerable.SingleOrDefault .

Method Komunikat
Single Sekwencja nie zawiera pasującego elementu
Single
SingleOrDefault
Sekwencja zawiera więcej niż jeden pasujący element

W poniższym przykładzie wywołanie Enumerable.Single metody zgłasza InvalidOperationException wyjątek, ponieważ sekwencja nie ma elementu większego niż 4.

using System;
using System.Linq;

public class EnumerableEx5
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var singleObject = dbQueryResults.Single(value => value > 4);

        // Display results.
        Console.WriteLine("{0} is the only value greater than 4", singleObject);
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let singleObject = dbQueryResults.Single(fun value -> value > 4)

// Display results.
printfn $"{singleObject} is the only value greater than 4"

// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains no matching element
//       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example4
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim singleObject = dbQueryResults.Single(Function(value) value > 4)

        ' Display results.
        Console.WriteLine("{0} is the only value greater than 4",
                         singleObject)
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains no matching element
'       at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

Poniższy przykład próbuje zapobiec wystąpieniu wyjątku InvalidOperationException , gdy sekwencja jest pusta, wywołując metodę Enumerable.SingleOrDefault . Jednak ponieważ ta sekwencja zwraca wiele elementów, których wartość jest większa niż 2, zgłasza InvalidOperationException również wyjątek.

using System;
using System.Linq;

public class EnumerableEx6
{
    public static void Main()
    {
        int[] dbQueryResults = { 1, 2, 3, 4 };

        var singleObject = dbQueryResults.SingleOrDefault(value => value > 2);

        if (singleObject != 0)
            Console.WriteLine("{0} is the only value greater than 2",
                              singleObject);
        else
            // Handle an empty collection.
            Console.WriteLine("No value is greater than 2");
    }
}
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains more than one matching element
//       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
//       at Example.Main()
open System
open System.Linq

let dbQueryResults = [| 1; 2; 3; 4 |]

let singleObject = dbQueryResults.SingleOrDefault(fun value -> value > 2)

if singleObject <> 0 then
    printfn $"{singleObject} is the only value greater than 2"
else
    // Handle an empty collection.
    printfn "No value is greater than 2"
    
// The example displays the following output:
//    Unhandled Exception: System.InvalidOperationException:
//       Sequence contains more than one matching element
//       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
//       at <StartupCode$fs>.main()
Imports System.Linq

Module Example5
    Public Sub Main()
        Dim dbQueryResults() As Integer = {1, 2, 3, 4}

        Dim singleObject = dbQueryResults.SingleOrDefault(Function(value) value > 2)

        If singleObject <> 0 Then
            Console.WriteLine("{0} is the only value greater than 2",
                             singleObject)
        Else
            ' Handle an empty collection.
            Console.WriteLine("No value is greater than 2")
        End If
    End Sub
End Module
' The example displays the following output:
'    Unhandled Exception: System.InvalidOperationException: 
'       Sequence contains more than one matching element
'       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
'       at Example.Main()

Enumerable.Single Wywołanie metody zakłada, że sekwencja lub sekwencja spełniająca określone kryteria zawiera tylko jeden element. Enumerable.SingleOrDefault Zakłada sekwencję z zerowym lub jednym wynikiem, ale nie więcej. Jeśli to założenie jest celowe ze swojej strony i te warunki nie są spełnione, ponowne wychwycenie lub złapanie wynik InvalidOperationException jest odpowiednie. W przeciwnym razie lub jeśli spodziewasz się, że wystąpią nieprawidłowe warunki z pewną częstotliwością, rozważ użycie innej Enumerable metody, takiej jak FirstOrDefault lub Where.

Dynamiczny dostęp do pól domeny między aplikacjami

Instrukcja OpCodes.Ldflda wspólnego języka pośredniego (CIL) zgłasza InvalidOperationException wyjątek, jeśli obiekt zawierający pole, którego adres próbujesz pobrać, nie znajduje się w domenie aplikacji, w której jest wykonywany kod. Adres pola można uzyskać tylko z domeny aplikacji, w której się znajduje.

Zgłaszanie wyjątku InvalidOperationException

Należy zgłosić InvalidOperationException wyjątek tylko wtedy, gdy stan obiektu z jakiegoś powodu nie obsługuje określonego wywołania metody. Oznacza to, że wywołanie metody jest prawidłowe w niektórych okolicznościach lub kontekstach, ale jest nieprawidłowe w innych.

Jeśli niepowodzenie wywołania metody jest spowodowane nieprawidłowymi argumentami, ArgumentException zamiast tego należy zgłosić jedną z jej klas ArgumentNullException pochodnych lub .ArgumentOutOfRangeException