InvalidOperationException Classe
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Exception levée en cas d'appel de méthode non valide pour l'état actuel de l'objet.
public ref class InvalidOperationException : Exception
public ref class InvalidOperationException : SystemException
public class InvalidOperationException : Exception
public class InvalidOperationException : SystemException
[System.Serializable]
public class InvalidOperationException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class InvalidOperationException : SystemException
type InvalidOperationException = class
inherit Exception
type InvalidOperationException = class
inherit SystemException
[<System.Serializable>]
type InvalidOperationException = class
inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type InvalidOperationException = class
inherit SystemException
Public Class InvalidOperationException
Inherits Exception
Public Class InvalidOperationException
Inherits SystemException
- Héritage
- Héritage
- Dérivé
- Attributs
Remarques
InvalidOperationException est utilisé dans les cas où l’échec d’appeler une méthode est dû à des raisons autres que des arguments non valides. En règle générale, elle est levée lorsque l’état d’un objet ne peut pas prendre en charge l’appel de méthode. Par exemple, une InvalidOperationException exception est levée par des méthodes telles que :
IEnumerator.MoveNext si les objets d’une collection sont modifiés après la création de l’énumérateur. Pour plus d’informations, consultez Modification d’une collection lors de son itération.
ResourceSet.GetString si le jeu de ressources est fermé avant l’appel de méthode.
XContainer.Add, si le ou les objets à ajouter entraînent un document XML mal structuré.
Méthode qui tente de manipuler l’interface utilisateur à partir d’un thread qui n’est pas le main ou le thread d’interface utilisateur.
Important
Étant donné que l’exception InvalidOperationException peut être levée dans un large éventail de circonstances, il est important de lire le message d’exception retourné par la Message propriété .
Dans cette section :
Certaines causes courantes des exceptions InvalidOperationException
Mise à jour d’un thread d’interface utilisateur à partir d’un thread non-interface utilisateur
Modification d’une collection lors de son itération
Tri d’un tableau ou d’une collection dont les objets ne peuvent pas être comparés
Conversion d’un T> nullable<en son type sous-jacent
Appel d’une méthode System.Linq.Enumerable sur une collection vide
Appel de Enumerable.Single ou Enumerable.SingleOrDefault sur une séquence sans élément
Accès dynamique au champ de domaine inter-applications
Levée d’une exception InvalidOperationException
Informations diverses
Certaines causes courantes des exceptions InvalidOperationException
Les sections suivantes montrent comment certains cas courants dans lesquels une InvalidOperationException exception est levée dans une application. La façon dont vous gérez le problème dépend de la situation spécifique. Toutefois, le plus souvent, l’exception résulte d’une erreur du développeur, et l’exception InvalidOperationException peut être anticipée et évitée.
Mise à jour d’un thread d’interface utilisateur à partir d’un thread non-interface utilisateur
Souvent, les threads de travail sont utilisés pour effectuer un travail en arrière-plan qui implique la collecte de données à afficher dans l’interface utilisateur d’une application. Toutefois, la plupart des infrastructures d’application d’interface utilisateur graphique (GUI) pour .NET, telles que Windows Forms et Windows Presentation Foundation (WPF), vous permettent d’accéder aux objets GUI uniquement à partir du thread qui crée et gère l’interface utilisateur (thread principal ou d’interface utilisateur). Un InvalidOperationException est levée lorsque vous essayez d’accéder à un élément d’interface utilisateur à partir d’un thread autre que le thread d’interface utilisateur. Le texte du message d’exception est affiché dans le tableau suivant.
Type d’application | Message |
---|---|
Application WPF | Le thread appelant ne peut pas accéder à cet objet, car un thread différent en est propriétaire. |
Application UWP | L’application a appelé une interface qui a été marshalée pour un thread différent. |
application Windows Forms | Opération inter-thread non valide : contrôlez « TextBox1 » accessible à partir d’un thread autre que le thread sur lequel il a été créé. |
Les infrastructures d’interface utilisateur pour .NET implémentent un modèle de répartiteur qui inclut une méthode pour case activée si un appel à un membre d’un élément d’interface utilisateur est exécuté sur le thread d’interface utilisateur, et d’autres méthodes pour planifier l’appel sur le thread d’interface utilisateur :
Dans les applications WPF, appelez la Dispatcher.CheckAccess méthode pour déterminer si une méthode est en cours d’exécution sur un thread autre que l’interface utilisateur. Elle retourne
true
si la méthode est en cours d’exécution sur le thread d’interface utilisateur etfalse
sinon. Appelez l’une des surcharges de la Dispatcher.Invoke méthode pour planifier l’appel sur le thread d’interface utilisateur.Dans les applications UWP, case activée la CoreDispatcher.HasThreadAccess propriété pour déterminer si une méthode s’exécute sur un thread autre que l’interface utilisateur. Appelez la CoreDispatcher.RunAsync méthode pour exécuter un délégué qui met à jour le thread d’interface utilisateur.
Dans Windows Forms applications, utilisez la Control.InvokeRequired propriété pour déterminer si une méthode s’exécute sur un thread autre que l’interface utilisateur. Appelez l’une des surcharges de la Control.Invoke méthode pour exécuter un délégué qui met à jour le thread d’interface utilisateur.
Les exemples suivants illustrent l’exception InvalidOperationException levée lorsque vous tentez de mettre à jour un élément d’interface utilisateur à partir d’un thread autre que le thread qui l’a créé. Chaque exemple nécessite la création de deux contrôles :
Contrôle de zone de texte nommé
textBox1
. Dans une application Windows Forms, vous devez définir sa Multiline propriété surtrue
.Contrôle de bouton nommé
threadExampleBtn
. L’exemple fournit un gestionnaire,ThreadsExampleBtn_Click
, pour l’événement duClick
bouton.
Dans chaque cas, le gestionnaire d’événements threadExampleBtn_Click
appelle la DoSomeWork
méthode deux fois. Le premier appel s’exécute de manière synchrone et réussit. Mais le deuxième appel, parce qu’il s’exécute de manière asynchrone sur un thread de pool de threads, tente de mettre à jour l’interface utilisateur à partir d’un thread autre que l’interface utilisateur. Il en résulte une InvalidOperationException exception.
Applications WPF et UWP
private async void threadExampleBtn_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = String.Empty;
textBox1.Text = "Simulating work on UI thread.\n";
DoSomeWork(20);
textBox1.Text += "Work completed...\n";
textBox1.Text += "Simulating work on non-UI thread.\n";
await Task.Run(() => DoSomeWork(1000));
textBox1.Text += "Work completed...\n";
}
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
var msg = String.Format("Some work completed in {0} ms.\n", milliseconds);
textBox1.Text += msg;
}
Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) Handles threadExampleBtn.Click
textBox1.Text = String.Empty
textBox1.Text = "Simulating work on UI thread." + vbCrLf
DoSomeWork(20)
textBox1.Text += "Work completed..." + vbCrLf
textBox1.Text += "Simulating work on non-UI thread." + vbCrLf
Await Task.Factory.StartNew(Sub()
DoSomeWork(1000)
End Sub)
textBox1.Text += "Work completed..." + vbCrLf
End Sub
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim msg = String.Format("Some work completed in {0} ms.", milliseconds) + vbCrLf
textBox1.Text += msg
End Sub
La version suivante de la DoSomeWork
méthode élimine l’exception dans une application WPF.
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
bool uiAccess = textBox1.Dispatcher.CheckAccess();
String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
milliseconds, uiAccess ? String.Empty : "non-");
if (uiAccess)
textBox1.Text += msg;
else
textBox1.Dispatcher.Invoke(() => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.CheckAccess()
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread",
milliseconds, If(uiAccess, String.Empty, "non-")) +
vbCrLf
If uiAccess Then
textBox1.Text += msg
Else
textBox1.Dispatcher.Invoke( Sub() textBox1.Text += msg)
End If
End Sub
La version suivante de la DoSomeWork
méthode élimine l’exception dans une application UWP.
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
bool uiAccess = textBox1.Dispatcher.HasThreadAccess;
String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
milliseconds, uiAccess ? String.Empty : "non-");
if (uiAccess)
textBox1.Text += msg;
else
await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.HasThreadAccess
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
milliseconds, If(uiAccess, String.Empty, "non-"))
If (uiAccess) Then
textBox1.Text += msg
Else
Await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() textBox1.Text += msg)
End If
End Sub
Applications 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 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
La version suivante de la DoSomeWork
méthode élimine l’exception dans une application 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
Modification d’une collection lors de son itération
L’instruction foreach
en C#, for...in
en F# ou For Each
en Visual Basic est utilisée pour itérer les membres d’une collection et pour lire ou modifier ses éléments individuels. Toutefois, il ne peut pas être utilisé pour ajouter ou supprimer des éléments de la collection. Cela lève une InvalidOperationException exception avec un message similaire à « La collection a été modifiée ; l’opération d’énumération peut ne pas s’exécuter. »
L’exemple suivant itère une collection d’entiers tente d’ajouter le carré de chaque entier à la collection. L’exemple lève un InvalidOperationException avec le premier appel à la List<T>.Add méthode.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
var numbers = new List<int>() { 1, 2, 3, 4, 5 };
foreach (var number in numbers) {
int square = (int) Math.Pow(number, 2);
Console.WriteLine("{0}^{1}", number, square);
Console.WriteLine("Adding {0} to the collection...\n", square);
numbers.Add(square);
}
}
}
// The example displays the following output:
// 1^1
// Adding 1 to the collection...
//
//
// Unhandled Exception: System.InvalidOperationException: Collection was modified;
// enumeration operation may not execute.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
// at Example.Main()
open System
let numbers = ResizeArray [| 1; 2; 3; 4; 5 |]
for number in numbers do
let square = Math.Pow(number, 2) |> int
printfn $"{number}^{square}"
printfn $"Adding {square} to the collection...\n"
numbers.Add square
// The example displays the following output:
// 1^1
// Adding 1 to the collection...
//
//
// Unhandled Exception: System.InvalidOperationException: Collection was modified
// enumeration operation may not execute.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
// at <StartupCode$fs>.main()
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } )
For Each number In numbers
Dim square As Integer = CInt(Math.Pow(number, 2))
Console.WriteLine("{0}^{1}", number, square)
Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
square)
numbers.Add(square)
Next
End Sub
End Module
' The example displays the following output:
' 1^1
' Adding 1 to the collection...
'
'
' Unhandled Exception: System.InvalidOperationException: Collection was modified;
' enumeration operation may not execute.
' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
' at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
' at Example.Main()
Vous pouvez éliminer l’exception de l’une des deux manières, en fonction de la logique de votre application :
Si des éléments doivent être ajoutés à la collection lors de son itération, vous pouvez l’itérer par index à l’aide de l’instruction
for
(for..to
en F#) au lieu deforeach
,for...in
ouFor Each
. L’exemple suivant utilise l’instruction for pour ajouter le carré de nombres de la collection à la 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
open System open System.Collections.Generic let numbers = ResizeArray [| 1; 2; 3; 4; 5 |] let upperBound = numbers.Count - 1 for i = 0 to upperBound do let square = Math.Pow(numbers[i], 2) |> int printfn $"{numbers[i]}^{square}" printfn $"Adding {square} to the collection...\n" numbers.Add square printfn "Elements now in the collection: " for number in numbers do printf $"{number} " // The example displays the following output: // 1^1 // Adding 1 to the collection... // // 2^4 // Adding 4 to the collection... // // 3^9 // Adding 9 to the collection... // // 4^16 // Adding 16 to the collection... // // 5^25 // Adding 25 to the collection... // // Elements now in the collection: // 1 2 3 4 5 1 4 9 16 25
Imports System.Collections.Generic Module Example Public Sub Main() Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) Dim upperBound = numbers.Count - 1 For ctr As Integer = 0 To upperBound Dim square As Integer = CInt(Math.Pow(numbers(ctr), 2)) Console.WriteLine("{0}^{1}", numbers(ctr), square) Console.WriteLine("Adding {0} to the collection..." + vbCrLf, square) numbers.Add(square) Next Console.WriteLine("Elements now in the collection: ") For Each number In numbers Console.Write("{0} ", number) Next End Sub End Module ' The example displays the following output: ' 1^1 ' Adding 1 to the collection... ' ' 2^4 ' Adding 4 to the collection... ' ' 3^9 ' Adding 9 to the collection... ' ' 4^16 ' Adding 16 to the collection... ' ' 5^25 ' Adding 25 to the collection... ' ' Elements now in the collection: ' 1 2 3 4 5 1 4 9 16 25
Notez que vous devez établir le nombre d’itérations avant d’itérer la collection en utilisant un compteur à l’intérieur de la boucle qui quittera la boucle de manière appropriée, en itérant vers l’arrière, de
Count
- 1 à 0, ou, comme l’exemple le fait, en affectant le nombre d’éléments du tableau à une variable et en l’utilisant pour établir la limite supérieure de la boucle. Sinon, si un élément est ajouté à la collection à chaque itération, une boucle sans fin se produit.S’il n’est pas nécessaire d’ajouter des éléments à la collection lors de son itération, vous pouvez stocker les éléments à ajouter dans une collection temporaire que vous ajoutez lorsque l’itération de la collection est terminée. L’exemple suivant utilise cette approche pour ajouter le carré de nombres d’une collection à une collection temporaire, puis pour combiner les collections en un seul objet de tableau.
using System; using System.Collections.Generic; public class Example { public static void Main() { var numbers = new List<int>() { 1, 2, 3, 4, 5 }; var temp = new List<int>(); // Square each number and store it in a temporary collection. foreach (var number in numbers) { int square = (int) Math.Pow(number, 2); temp.Add(square); } // Combine the numbers into a single array. int[] combined = new int[numbers.Count + temp.Count]; Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count); Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count); // Iterate the array. foreach (var value in combined) Console.Write("{0} ", value); } } // The example displays the following output: // 1 2 3 4 5 1 4 9 16 25
open System open System.Collections.Generic let numbers = ResizeArray [| 1; 2; 3; 4; 5 |] let temp = ResizeArray() // Square each number and store it in a temporary collection. for number in numbers do let square = Math.Pow(number, 2) |> int temp.Add square // Combine the numbers into a single array. let combined = Array.zeroCreate<int> (numbers.Count + temp.Count) Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count) Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count) // Iterate the array. for value in combined do printf $"{value} " // The example displays the following output: // 1 2 3 4 5 1 4 9 16 25
Imports System.Collections.Generic Module Example Public Sub Main() Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) Dim temp As New List(Of Integer)() ' Square each number and store it in a temporary collection. For Each number In numbers Dim square As Integer = CInt(Math.Pow(number, 2)) temp.Add(square) Next ' Combine the numbers into a single array. Dim combined(numbers.Count + temp.Count - 1) As Integer Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count) Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count) ' Iterate the array. For Each value In combined Console.Write("{0} ", value) Next End Sub End Module ' The example displays the following output: ' 1 2 3 4 5 1 4 9 16 25
Tri d’un tableau ou d’une collection dont les objets ne peuvent pas être comparés
Les méthodes de tri à usage général, telles que la Array.Sort(Array) méthode ou la List<T>.Sort() méthode, nécessitent généralement qu’au moins un des objets à trier implémente l’interface IComparable<T>IComparable ou . Si ce n’est pas le cas, la collection ou le tableau ne peut pas être trié et la méthode lève une InvalidOperationException exception. L’exemple suivant définit une Person
classe, stocke deux Person
objets dans un objet générique List<T> et tente de les trier. Comme le montre la sortie de l’exemple, l’appel à la List<T>.Sort() méthode lève un InvalidOperationException.
using System;
using System.Collections.Generic;
public class Person
{
public Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
public String FirstName { get; set; }
public String LastName { get; set; }
}
public class Example
{
public static void Main()
{
var people = new List<Person>();
people.Add(new Person("John", "Doe"));
people.Add(new Person("Jane", "Doe"));
people.Sort();
foreach (var person in people)
Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
// System.ArgumentException: At least one object must implement IComparable.
// at System.Collections.Comparer.Compare(Object a, Object b)
// at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
// at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// --- End of inner exception stack trace ---
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
// at Example.Main()
type Person(firstName: string, lastName: string) =
member val FirstName = firstName with get, set
member val LastName = lastName with get, set
let people = ResizeArray()
people.Add(Person("John", "Doe"))
people.Add(Person("Jane", "Doe"))
people.Sort()
for person in people do
printfn $"{person.FirstName} {person.LastName}"
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
// System.ArgumentException: At least one object must implement IComparable.
// at System.Collections.Comparer.Compare(Object a, Object b)
// at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
// at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// --- End of inner exception stack trace ---
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
// at <StartupCode$fs>.main()
Imports System.Collections.Generic
Public Class Person
Public Sub New(fName As String, lName As String)
FirstName = fName
LastName = lName
End Sub
Public Property FirstName As String
Public Property LastName As String
End Class
Module Example
Public Sub Main()
Dim people As New List(Of Person)()
people.Add(New Person("John", "Doe"))
people.Add(New Person("Jane", "Doe"))
people.Sort()
For Each person In people
Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
Next
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
' System.ArgumentException: At least one object must implement IComparable.
' at System.Collections.Comparer.Compare(Object a, Object b)
' at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
' at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
' --- End of inner exception stack trace ---
' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
' at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
' at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
' at Example.Main()
Vous pouvez éliminer l’exception de l’une des trois manières suivantes :
Si vous pouvez posséder le type que vous essayez de trier (autrement dit, si vous contrôlez son code source), vous pouvez le modifier pour implémenter l’interface IComparable<T>IComparable ou. Pour cela, vous devez implémenter la IComparable<T>.CompareTo méthode ou CompareTo . L’ajout d’une implémentation d’interface à un type existant n’est pas une modification cassant.
L’exemple suivant utilise cette approche pour fournir une IComparable<T> implémentation pour la
Person
classe . Vous pouvez toujours appeler la méthode de tri général de la collection ou du tableau et, comme le montre la sortie de l’exemple, la collection trie correctement.using System; using System.Collections.Generic; public class Person : IComparable<Person> { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } public int CompareTo(Person other) { return String.Format("{0} {1}", LastName, FirstName). CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName)); } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("Jane", "Doe")); people.Sort(); foreach (var person in people) Console.WriteLine("{0} {1}", person.FirstName, person.LastName); } } // The example displays the following output: // Jane Doe // John Doe
open System type Person(firstName: string, lastName: string) = member val FirstName = firstName with get, set member val LastName = lastName with get, set interface IComparable<Person> with member this.CompareTo(other) = compare $"{this.LastName} {this.FirstName}" $"{other.LastName} {other.FirstName}" let people = ResizeArray() people.Add(new Person("John", "Doe")) people.Add(new Person("Jane", "Doe")) people.Sort() for person in people do printfn $"{person.FirstName} {person.LastName}" // The example displays the following output: // Jane Doe // John Doe
Imports System.Collections.Generic Public Class Person : Implements IComparable(Of Person) Public Sub New(fName As String, lName As String) FirstName = fName LastName = lName End Sub Public Property FirstName As String Public Property LastName As String Public Function CompareTo(other As Person) As Integer _ Implements IComparable(Of Person).CompareTo Return String.Format("{0} {1}", LastName, FirstName). CompareTo(String.Format("{0} {1}", other.LastName, other.FirstName)) End Function End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("Jane", "Doe")) people.Sort() For Each person In people Console.WriteLine("{0} {1}", person.FirstName, person.LastName) Next End Sub End Module ' The example displays the following output: ' Jane Doe ' John Doe
Si vous ne pouvez pas modifier le code source du type que vous essayez de trier, vous pouvez définir une classe de tri à usage spécial qui implémente l’interface IComparer<T> . Vous pouvez appeler une surcharge de la
Sort
méthode qui inclut un IComparer<T> paramètre. Cette approche est particulièrement utile si vous souhaitez développer une classe de tri spécialisée qui peut trier des objets en fonction de plusieurs critères.L’exemple suivant utilise l’approche en développant une classe personnalisée
PersonComparer
utilisée pour trierPerson
les collections. Il transmet ensuite une instance de cette classe à la List<T>.Sort(IComparer<T>) méthode .using System; using System.Collections.Generic; public class Person { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } } public class PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("Jane", "Doe")); people.Sort(new PersonComparer()); foreach (var person in people) Console.WriteLine("{0} {1}", person.FirstName, person.LastName); } } // The example displays the following output: // Jane Doe // John Doe
open System open System.Collections.Generic type Person(firstName, lastName) = member val FirstName = firstName with get, set member val LastName = lastName with get, set type PersonComparer() = interface IComparer<Person> with member _.Compare(x: Person, y: Person) = $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}" let people = ResizeArray() people.Add(Person("John", "Doe")) people.Add(Person("Jane", "Doe")) people.Sort(PersonComparer()) for person in people do printfn $"{person.FirstName} {person.LastName}" // The example displays the following output: // Jane Doe // John Doe
Imports System.Collections.Generic Public Class Person Public Sub New(fName As String, lName As String) FirstName = fName LastName = lName End Sub Public Property FirstName As String Public Property LastName As String End Class Public Class PersonComparer : Implements IComparer(Of Person) Public Function Compare(x As Person, y As Person) As Integer _ Implements IComparer(Of Person).Compare Return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) End Function End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("Jane", "Doe")) people.Sort(New PersonComparer()) For Each person In people Console.WriteLine("{0} {1}", person.FirstName, person.LastName) Next End Sub End Module ' The example displays the following output: ' Jane Doe ' John Doe
Si vous ne pouvez pas modifier le code source du type que vous essayez de trier, vous pouvez créer un Comparison<T> délégué pour effectuer le tri. La signature du délégué est
Function Comparison(Of T)(x As T, y As T) As Integer
int Comparison<T>(T x, T y)
L’exemple suivant utilise l’approche en définissant une
PersonComparison
méthode qui correspond à la signature du Comparison<T> délégué. Il transmet ensuite ce délégué à la List<T>.Sort(Comparison<T>) méthode .using System; using System.Collections.Generic; public class Person { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("Jane", "Doe")); people.Sort(PersonComparison); foreach (var person in people) Console.WriteLine("{0} {1}", person.FirstName, person.LastName); } public static int PersonComparison(Person x, Person y) { return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); } } // The example displays the following output: // Jane Doe // John Doe
open System open System.Collections.Generic type Person(firstName, lastName) = member val FirstName = firstName with get, set member val LastName = lastName with get, set let personComparison (x: Person) (y: Person) = $"{x.LastName} {x.FirstName}".CompareTo $"{y.LastName} {y.FirstName}" let people = ResizeArray() people.Add(Person("John", "Doe")) people.Add(Person("Jane", "Doe")) people.Sort personComparison for person in people do printfn $"{person.FirstName} {person.LastName}" // The example displays the following output: // Jane Doe // John Doe
Imports System.Collections.Generic Public Class Person Public Sub New(fName As String, lName As String) FirstName = fName LastName = lName End Sub Public Property FirstName As String Public Property LastName As String End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("Jane", "Doe")) people.Sort(AddressOf PersonComparison) For Each person In people Console.WriteLine("{0} {1}", person.FirstName, person.LastName) Next End Sub Public Function PersonComparison(x As Person, y As Person) As Integer Return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) End Function End Module ' The example displays the following output: ' Jane Doe ' John Doe
Conversion d’un T> nullable<dans son type sous-jacent
La tentative de cast d’une Nullable<T> valeur qui correspond null
à son type sous-jacent lève une InvalidOperationException exception et affiche le message d’erreur « L’objet Nullable doit avoir une valeur.
L’exemple suivant lève une InvalidOperationException exception lorsqu’il tente d’itérer un tableau qui inclut une Nullable(Of Integer)
valeur.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
var queryResult = new int?[] { 1, 2, null, 4 };
var map = queryResult.Select(nullableInt => (int)nullableInt);
// Display list.
foreach (var num in map)
Console.Write("{0} ", num);
Console.WriteLine();
}
}
// The example displays the following output:
// 1 2
// Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at Example.<Main>b__0(Nullable`1 nullableInt)
// at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
// at Example.Main()
open System
open System.Linq
let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let map = queryResult.Select(fun nullableInt -> nullableInt.Value)
// Display list.
for num in map do
printf $"{num} "
printfn ""
// The example displays the following output:
// 1 2
// Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at Example.<Main>b__0(Nullable`1 nullableInt)
// at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
// at <StartupCode$fs>.main()
Imports System.Linq
Module Example
Public Sub Main()
Dim queryResult = New Integer?() { 1, 2, Nothing, 4 }
Dim map = queryResult.Select(Function(nullableInt) CInt(nullableInt))
' Display list.
For Each num In map
Console.Write("{0} ", num)
Next
Console.WriteLine()
End Sub
End Module
' The example displays thIe following output:
' 1 2
' Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
' at Example.<Main>b__0(Nullable`1 nullableInt)
' at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
' at Example.Main()
Pour empêcher l’exception :
Utilisez la Nullable<T>.HasValue propriété pour sélectionner uniquement les éléments qui ne sont pas
null
.Appelez l’une Nullable<T>.GetValueOrDefault des surcharges pour fournir une valeur par défaut pour une
null
valeur.
L’exemple suivant fait les deux pour éviter l’exception InvalidOperationException .
using System;
using System.Linq;
public class Example
{
public static void Main()
{
var queryResult = new int?[] { 1, 2, null, 4 };
var numbers = queryResult.Select(nullableInt => (int)nullableInt.GetValueOrDefault());
// Display list using Nullable<int>.HasValue.
foreach (var number in numbers)
Console.Write("{0} ", number);
Console.WriteLine();
numbers = queryResult.Select(nullableInt => (int) (nullableInt.HasValue ? nullableInt : -1));
// Display list using Nullable<int>.GetValueOrDefault.
foreach (var number in numbers)
Console.Write("{0} ", number);
Console.WriteLine();
}
}
// The example displays the following output:
// 1 2 0 4
// 1 2 -1 4
open System
open System.Linq
let queryResult = [| Nullable 1; Nullable 2; Nullable(); Nullable 4 |]
let numbers = queryResult.Select(fun nullableInt -> nullableInt.GetValueOrDefault())
// Display list using Nullable<int>.HasValue.
for number in numbers do
printf $"{number} "
printfn ""
let numbers2 = queryResult.Select(fun nullableInt -> if nullableInt.HasValue then nullableInt.Value else -1)
// Display list using Nullable<int>.GetValueOrDefault.
for number in numbers2 do
printf $"{number} "
printfn ""
// The example displays the following output:
// 1 2 0 4
// 1 2 -1 4
Imports System.Linq
Module Example
Public Sub Main()
Dim queryResult = New Integer?() { 1, 2, Nothing, 4 }
Dim numbers = queryResult.Select(Function(nullableInt) _
CInt(nullableInt.GetValueOrDefault()))
' Display list.
For Each number In numbers
Console.Write("{0} ", number)
Next
Console.WriteLine()
' Use -1 to indicate a missing values.
numbers = queryResult.Select(Function(nullableInt) _
CInt(If(nullableInt.HasValue, nullableInt, -1)))
' Display list.
For Each number In numbers
Console.Write("{0} ", number)
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' 1 2 0 4
' 1 2 -1 4
Appel d’une méthode System.Linq.Enumerable sur une collection vide
Les Enumerable.Aggregateméthodes , Enumerable.Average, Enumerable.First, Enumerable.MaxEnumerable.LastEnumerable.Min, , Enumerable.Single, et Enumerable.SingleOrDefault effectuent des opérations sur une séquence et retournent un résultat unique. Certaines surcharges de ces méthodes lèvent une InvalidOperationException exception lorsque la séquence est vide, tandis que d’autres surcharges retournent null
. La Enumerable.SingleOrDefault méthode lève également une InvalidOperationException exception lorsque la séquence contient plusieurs éléments.
Notes
La plupart des méthodes qui lèvent une InvalidOperationException exception sont des surcharges. Veillez à comprendre le comportement de la surcharge que vous choisissez.
Le tableau suivant répertorie les messages d’exception des objets d’exception InvalidOperationException levées par les appels à certaines System.Linq.Enumerable méthodes.
Méthode | Message |
---|---|
Aggregate Average Last Max Min |
La séquence ne contient aucun élément |
First |
La séquence ne contient aucun élément correspondant |
Single SingleOrDefault |
La séquence contient plusieurs éléments correspondants |
La façon dont vous éliminez ou gérez l’exception dépend des hypothèses de votre application et de la méthode particulière que vous appelez.
Lorsque vous appelez délibérément l’une de ces méthodes sans vérifier la présence d’une séquence vide, vous supposez que la séquence n’est pas vide et qu’une séquence vide est une occurrence inattendue. Dans ce cas, l’interceptation ou la reserowing de l’exception est appropriée.
Si votre échec à case activée pour une séquence vide a été involontaire, vous pouvez appeler l’une des surcharges de la Enumerable.Any surcharge pour déterminer si une séquence contient des éléments.
Conseil
L’appel de la Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) méthode avant de générer une séquence peut améliorer les performances si les données à traiter peuvent contenir un grand nombre d’éléments ou si l’opération qui génère la séquence est coûteuse.
Si vous avez appelé une méthode telle que Enumerable.First, Enumerable.Lastou Enumerable.Single, vous pouvez remplacer une autre méthode, telle que Enumerable.FirstOrDefault, Enumerable.LastOrDefaultou Enumerable.SingleOrDefault, qui retourne une valeur par défaut au lieu d’un membre de la séquence.
Les exemples fournissent des détails supplémentaires.
L’exemple suivant utilise la Enumerable.Average méthode pour calculer la moyenne d’une séquence dont les valeurs sont supérieures à 4. Étant donné qu’aucune valeur du tableau d’origine ne dépasse 4, aucune valeur n’est incluse dans la séquence et la méthode lève une 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()
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()
L’exception peut être supprimée en appelant la Any méthode pour déterminer si la séquence contient des éléments avant d’appeler la méthode qui traite la séquence, comme le montre l’exemple suivant.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var moreThan4 = dbQueryResults.Where(num => num > 4);
if(moreThan4.Any())
Console.WriteLine("Average value of numbers greater than 4: {0}:",
moreThan4.Average());
else
// handle empty collection
Console.WriteLine("The dataset has no values greater than 4.");
}
}
// The example displays the following output:
// The dataset has no values greater than 4.
open System
open System.Linq
let dbQueryResults = [| 1; 2; 3; 4 |]
let moreThan4 =
dbQueryResults.Where(fun num -> num > 4)
if moreThan4.Any() then
printfn $"Average value of numbers greater than 4: {moreThan4.Average()}:"
else
// handle empty collection
printfn "The dataset has no values greater than 4."
// The example displays the following output:
// The dataset has no values greater than 4.
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim moreThan4 = dbQueryResults.Where(Function(num) num > 4)
If moreThan4.Any() Then
Console.WriteLine("Average value of numbers greater than 4: {0}:",
moreThan4.Average())
Else
' Handle empty collection.
Console.WriteLine("The dataset has no values greater than 4.")
End If
End Sub
End Module
' The example displays the following output:
' The dataset has no values greater than 4.
La Enumerable.First méthode retourne le premier élément d’une séquence ou le premier élément d’une séquence qui répond à une condition spécifiée. Si la séquence est vide et n’a donc pas de premier élément, elle lève une InvalidOperationException exception.
Dans l’exemple suivant, la Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) méthode lève une InvalidOperationException exception, car le tableau dbQueryResults ne contient pas d’élément supérieur à 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()
open System
open System.Linq
let dbQueryResults = [| 1; 2; 3; 4 |]
let firstNum = dbQueryResults.First(fun n -> n > 4)
printfn $"The first value greater than 4 is {firstNum}"
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains no matching element
// at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
// at <StartupCode$fs>.main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim firstNum = dbQueryResults.First(Function(n) n > 4)
Console.WriteLine("The first value greater than 4 is {0}",
firstNum)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains no matching element
' at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
Vous pouvez appeler la Enumerable.FirstOrDefault méthode au lieu de Enumerable.First retourner une valeur spécifiée ou par défaut. Si la méthode ne trouve pas de premier élément dans la séquence, elle retourne la valeur par défaut pour ce type de données. La valeur par défaut est null
pour un type de référence, zéro pour un type de données numérique et DateTime.MinValue pour le DateTime type.
Notes
L’interprétation de la valeur retournée par la Enumerable.FirstOrDefault méthode est souvent compliquée par le fait que la valeur par défaut du type peut être une valeur valide dans la séquence. Dans ce cas, vous appelez la Enumerable.Any méthode pour déterminer si la séquence a des membres valides avant d’appeler la Enumerable.First méthode.
L’exemple suivant appelle la Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) méthode pour empêcher l’exception InvalidOperationException levée dans l’exemple précédent.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var firstNum = dbQueryResults.FirstOrDefault(n => n > 4);
if (firstNum == 0)
Console.WriteLine("No value is greater than 4.");
else
Console.WriteLine("The first value greater than 4 is {0}",
firstNum);
}
}
// The example displays the following output:
// No value is greater than 4.
open System
open System.Linq
let dbQueryResults = [| 1; 2; 3; 4 |]
let firstNum = dbQueryResults.FirstOrDefault(fun n -> n > 4)
if firstNum = 0 then
printfn "No value is greater than 4."
else
printfn $"The first value greater than 4 is {firstNum}"
// The example displays the following output:
// No value is greater than 4.
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim firstNum = dbQueryResults.FirstOrDefault(Function(n) n > 4)
If firstNum = 0 Then
Console.WriteLIne("No value is greater than 4.")
Else
Console.WriteLine("The first value greater than 4 is {0}",
firstNum)
End If
End Sub
End Module
' The example displays the following output:
' No value is greater than 4.
Appel de Enumerable.Single ou Enumerable.SingleOrDefault sur une séquence sans élément
La Enumerable.Single méthode retourne le seul élément d’une séquence ou le seul élément d’une séquence qui répond à une condition spécifiée. S’il n’y a aucun élément dans la séquence, ou s’il existe plusieurs éléments , la méthode lève une InvalidOperationException exception.
Vous pouvez utiliser la Enumerable.SingleOrDefault méthode pour retourner une valeur par défaut au lieu de lever une exception lorsque la séquence ne contient aucun élément. Toutefois, la Enumerable.SingleOrDefault méthode lève toujours une InvalidOperationException exception lorsque la séquence contient plusieurs éléments.
Le tableau suivant répertorie les messages d’exception des objets d’exception InvalidOperationException levées par les Enumerable.Single appels aux méthodes et Enumerable.SingleOrDefault .
Méthode | Message |
---|---|
Single |
La séquence ne contient aucun élément correspondant |
Single SingleOrDefault |
La séquence contient plusieurs éléments correspondants |
Dans l’exemple suivant, l’appel à la Enumerable.Single méthode lève une InvalidOperationException exception, car la séquence n’a pas d’élément supérieur à 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()
open System
open System.Linq
let dbQueryResults = [| 1; 2; 3; 4 |]
let singleObject = dbQueryResults.Single(fun value -> value > 4)
// Display results.
printfn $"{singleObject} is the only value greater than 4"
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains no matching element
// at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
// at <StartupCode$fs>.main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim singleObject = dbQueryResults.Single(Function(value) value > 4)
' Display results.
Console.WriteLine("{0} is the only value greater than 4",
singleObject)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains no matching element
' at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
L’exemple suivant tente d’empêcher l’exception InvalidOperationException levée lorsqu’une séquence est vide en appelant plutôt la Enumerable.SingleOrDefault méthode . Toutefois, comme cette séquence retourne plusieurs éléments dont la valeur est supérieure à 2, elle lève également une 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()
open System
open System.Linq
let dbQueryResults = [| 1; 2; 3; 4 |]
let singleObject = dbQueryResults.SingleOrDefault(fun value -> value > 2)
if singleObject <> 0 then
printfn $"{singleObject} is the only value greater than 2"
else
// Handle an empty collection.
printfn "No value is greater than 2"
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains more than one matching element
// at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
// at <StartupCode$fs>.main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim singleObject = dbQueryResults.SingleOrDefault(Function(value) value > 2)
If singleObject <> 0 Then
Console.WriteLine("{0} is the only value greater than 2",
singleObject)
Else
' Handle an empty collection.
Console.WriteLine("No value is greater than 2")
End If
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains more than one matching element
' at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
L’appel de la Enumerable.Single méthode suppose qu’une séquence ou la séquence qui répond aux critères spécifiés ne contient qu’un seul élément. Enumerable.SingleOrDefault suppose une séquence avec zéro ou un résultat, mais pas plus. Si cette hypothèse est délibérée de votre part et que ces conditions ne sont pas remplies, il est approprié de repousser ou d’attraper le résultat.InvalidOperationException Sinon, ou si vous vous attendez à ce que des conditions non valides se produisent avec une certaine fréquence, vous devez envisager d’utiliser une autre Enumerable méthode, telle que FirstOrDefault ou Where.
Accès dynamique au champ inter-applications
L’instruction OpCodes.Ldflda MSIL (Microsoft Intermediate Language) lève une InvalidOperationException exception si l’objet contenant le champ dont vous essayez de récupérer l’adresse ne se trouve pas dans le domaine d’application dans lequel votre code s’exécute. L’adresse d’un champ est accessible uniquement à partir du domaine d’application dans lequel il réside.
Levée d’une exception InvalidOperationException
Vous devez lever une InvalidOperationException exception uniquement lorsque l’état de votre objet pour une raison quelconque ne prend pas en charge un appel de méthode particulier. Autrement dit, l’appel de méthode est valide dans certaines circonstances ou contextes, mais n’est pas valide dans d’autres.
Si l’échec de l’appel de méthode est dû à des arguments non valides, ou ArgumentException l’une de ses classes dérivées, ArgumentNullException ou ArgumentOutOfRangeException, doit être levée à la place.
Informations diverses
InvalidOperationException utilise le COR_E_INVALIDOPERATION HRESULT, qui a la valeur 0x80131509.
Pour obtenir la liste des valeurs initiales des propriétés d’une instance de InvalidOperationException, consultez le InvalidOperationException constructeurs.
Constructeurs
InvalidOperationException() |
Initialise une nouvelle instance de la classe InvalidOperationException. |
InvalidOperationException(SerializationInfo, StreamingContext) |
Obsolète.
Initialise une nouvelle instance de la classe InvalidOperationException avec des données sérialisées. |
InvalidOperationException(String) |
Initialise une nouvelle instance de la classe InvalidOperationException avec un message d'erreur spécifié. |
InvalidOperationException(String, Exception) |
Initialise une nouvelle instance de la classe InvalidOperationException avec un message d'erreur spécifié et une référence à l'exception interne ayant provoqué cette exception. |
Propriétés
Data |
Obtient une collection de paires clé/valeur qui fournissent des informations définies par l'utilisateur supplémentaires sur l'exception. (Hérité de Exception) |
HelpLink |
Obtient ou définit un lien vers le fichier d'aide associé à cette exception. (Hérité de Exception) |
HResult |
Obtient ou définit HRESULT, valeur numérique codée qui est assignée à une exception spécifique. (Hérité de Exception) |
InnerException |
Obtient l'instance Exception qui a provoqué l'exception actuelle. (Hérité de Exception) |
Message |
Obtient un message qui décrit l'exception active. (Hérité de Exception) |
Source |
Obtient ou définit le nom de l'application ou de l'objet qui est à l'origine de l'erreur. (Hérité de Exception) |
StackTrace |
Obtient une représentation sous forme de chaîne des frames immédiats sur la pile des appels. (Hérité de Exception) |
TargetSite |
Obtient la méthode qui lève l'exception actuelle. (Hérité de Exception) |
Méthodes
Equals(Object) |
Détermine si l'objet spécifié est égal à l'objet actuel. (Hérité de Object) |
GetBaseException() |
En cas de substitution dans une classe dérivée, retourne la Exception qui est à l'origine d'une ou de plusieurs exceptions ultérieures. (Hérité de Exception) |
GetHashCode() |
Fait office de fonction de hachage par défaut. (Hérité de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Obsolète.
En cas de substitution dans une classe dérivée, définit SerializationInfo avec des informations sur l'exception. (Hérité de Exception) |
GetType() |
Obtient le type au moment de l'exécution de l'instance actuelle. (Hérité de Exception) |
MemberwiseClone() |
Crée une copie superficielle du Object actuel. (Hérité de Object) |
ToString() |
Crée et retourne une chaîne représentant l'exception actuelle. (Hérité de Exception) |
Événements
SerializeObjectState |
Obsolète.
Se produit quand une exception est sérialisée pour créer un objet d'état d'exception qui contient des données sérialisées concernant l'exception. (Hérité de Exception) |