InvalidOperationException Classe
Definição
A exceção que é gerada quando uma chamada de método é inválida para o estado atual do objeto.The exception that is thrown when a method call is invalid for the object's current state.
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
- Herança
- Herança
- Derivado
- Atributos
Comentários
InvalidOperationException é usado em casos em que a falha ao invocar um método é causada por motivos diferentes de argumentos inválidos.InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Normalmente, ele é gerado quando o estado de um objeto não pode dar suporte à chamada de método.Typically, it is thrown when the state of an object cannot support the method call. Por exemplo, uma InvalidOperationException exceção é lançada por métodos como:For example, an InvalidOperationException exception is thrown by methods such as:
IEnumerator.MoveNext Se os objetos de uma coleção forem modificados depois que o enumerador for criado.IEnumerator.MoveNext if objects of a collection are modified after the enumerator is created. Para obter mais informações, consulte alterando uma coleção ao iterar.For more information, see Changing a collection while iterating it.
ResourceSet.GetString Se o conjunto de recursos for fechado antes da chamada do método ser feita.ResourceSet.GetString if the resource set is closed before the method call is made.
XContainer.Add, se o objeto ou objetos a serem adicionados resultarem em um documento XML incorretamente estruturado.XContainer.Add, if the object or objects to be added would result in an incorrectly structured XML document.
Um método que tenta manipular a interface do usuário de um thread que não é o thread principal ou de interface do usuário.A method that attempts to manipulate the UI from a thread that is not the main or UI thread.
Importante
Como a InvalidOperationException exceção pode ser lançada em uma ampla variedade de circunstâncias, é importante ler a mensagem de exceção retornada pela Message propriedade.Because the InvalidOperationException exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the Message property.
Nesta seção:In this section:
Algumas causas comuns de exceções InvalidOperationException Some common causes of InvalidOperationException exceptions
Atualizando um thread de interface do usuário de um thread que não é da interface do usuárioUpdating a UI thread from a non-UI thread
Alterando uma coleção ao iterarChanging a collection while iterating it
Classificando uma matriz ou coleção cujos objetos não podem ser comparadosSorting an array or collection whose objects cannot be compared
Convertendo um < T Anulável > que é nulo para seu tipo subjacente Casting a Nullable<T> that is null to its underlying type
Chamando um método System. Linq. Enumerable em uma coleção vaziaCalling a System.Linq.Enumerable method on an empty collection
Chamando Enumerable. single ou Enumerable. SingleOrDefault em uma sequência sem um elementoCalling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
Acesso dinâmico ao campo de domínio entre aplicativosDynamic cross-application domain field access
Gerando uma exceção InvalidOperationExceptionThrowing an InvalidOperationException exception
Informações diversasMiscellaneous information
Algumas causas comuns de exceções InvalidOperationExceptionSome common causes of InvalidOperationException exceptions
As seções a seguir mostram como alguns casos comuns nos quais a InvalidOperationException exceção é lançada em um aplicativo.The following sections show how some common cases in which in InvalidOperationException exception is thrown in an app. A maneira como você lida com o problema depende da situação específica.How you handle the issue depends on the specific situation. No entanto, geralmente a exceção resulta de erro do desenvolvedor e a InvalidOperationException exceção pode ser antecipada e evitada.Most commonly, however, the exception results from developer error, and the InvalidOperationException exception can be anticipated and avoided.
Atualizando um thread de interface do usuário de um thread que não é da interface do usuárioUpdating a UI thread from a non-UI thread
Geralmente, os threads de trabalho são usados para executar um trabalho em segundo plano que envolve a coleta de dados a serem exibidos na interface do usuário de um aplicativo.Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. No entanto,However. a maioria das estruturas de aplicativo GUI (interface gráfica do usuário) para o .NET Framework, como Windows Forms e Windows Presentation Foundation (WPF), permite que você acesse objetos GUI somente do thread que cria e gerencia a interface do usuário (o thread principal ou de interface do usuário).most GUI (graphical user interface) application frameworks for the .NET Framework, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). Um InvalidOperationException é gerado quando você tenta acessar um elemento de interface do usuário de um thread diferente do thread da interface do usuário.An InvalidOperationException is thrown when you try to access a UI element from a thread other than the UI thread. O texto da mensagem de exceção é mostrado na tabela a seguir.The text of the exception message is shown in the following table.
Tipo de aplicativoApplication Type | MensagemMessage |
---|---|
Aplicativo WPFWPF app | O thread de chamada não pode acessar esse objeto porque um thread diferente o possui.The calling thread cannot access this object because a different thread owns it. |
Aplicativo UWPUWP app | O aplicativo chamou uma interface que foi empacotada para um thread diferente.The application called an interface that was marshaled for a different thread. |
Windows Forms aplicativoWindows Forms app | Operação entre threads inválida: controle "TextBox1" acessado de um thread diferente do thread no qual ele foi criado.Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on. |
As estruturas de interface do usuário para o .NET Framework implementam um padrão Dispatcher que inclui um método para verificar se uma chamada para um membro de um elemento de interface do usuário está sendo executada no thread da interface do usuário e outros métodos para agendar a chamada no thread da interface do usuário:UI frameworks for the .NET Framework implement a dispatcher pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread:
Em aplicativos do WPF, chame o Dispatcher.CheckAccess método para determinar se um método está sendo executado em um thread que não seja da interface do usuário.In WPF apps, call the Dispatcher.CheckAccess method to determine if a method is running on a non-UI thread. Ele retornará
true
se o método estiver sendo executado no thread da interface do usuário efalse
, caso contrário.It returnstrue
if the method is running on the UI thread andfalse
otherwise. Chame uma das sobrecargas do Dispatcher.Invoke método para agendar a chamada no thread da interface do usuário.Call one of the overloads of the Dispatcher.Invoke method to schedule the call on the UI thread.Em aplicativos UWP, verifique a CoreDispatcher.HasThreadAccess propriedade para determinar se um método está sendo executado em um thread que não seja de interface do usuário.In UWP apps, check the CoreDispatcher.HasThreadAccess property to determine if a method is running on a non-UI thread. Chame o CoreDispatcher.RunAsync método para executar um delegado que atualiza o thread da interface do usuário.Call the CoreDispatcher.RunAsync method to execute a delegate that updates the UI thread.
Em Windows Forms aplicativos, use a Control.InvokeRequired propriedade para determinar se um método está sendo executado em um thread que não seja da interface do usuário.In Windows Forms apps, use the Control.InvokeRequired property to determine if a method is running on a non-UI thread. Chame uma das sobrecargas do Control.Invoke método para executar um delegado que atualiza o thread da interface do usuário.Call one of the overloads of the Control.Invoke method to execute a delegate that updates the UI thread.
Os exemplos a seguir ilustram a InvalidOperationException exceção que é lançada quando você tenta atualizar um elemento de interface do usuário de um thread diferente do thread que o criou.The following examples illustrate the InvalidOperationException exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Cada exemplo requer que você crie dois controles:Each example requires that you create two controls:
Um controle de caixa de texto chamado
textBox1
.A text box control namedtextBox1
. Em um aplicativo Windows Forms, você deve definir sua Multiline propriedade comotrue
.In a Windows Forms app, you should set its Multiline property totrue
.Um controle de botão chamado
threadExampleBtn
.A button control namedthreadExampleBtn
. O exemplo fornece um manipulador,ThreadsExampleBtn_Click
, para o evento do botãoClick
.The example provides a handler,ThreadsExampleBtn_Click
, for the button'sClick
event.
Em cada caso, o threadExampleBtn_Click
manipulador de eventos chama o DoSomeWork
método duas vezes.In each case, the threadExampleBtn_Click
event handler calls the DoSomeWork
method twice. A primeira chamada é executada de forma síncrona e com sucesso.The first call runs synchronously and succeeds. Mas a segunda chamada, porque ela é executada de forma assíncrona em um thread do pool de threads, tenta atualizar a interface do usuário de um thread que não seja da interface do usuário.But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. Isso resulta em uma InvalidOperationException exceção.This results in a InvalidOperationException exception.
Aplicativos do WPF e UWPWPF and UWP apps
private async void threadExampleBtn_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = String.Empty;
textBox1.Text = "Simulating work on UI thread.\n";
DoSomeWork(20);
textBox1.Text += "Work completed...\n";
textBox1.Text += "Simulating work on non-UI thread.\n";
await Task.Run( () => DoSomeWork(1000));
textBox1.Text += "Work completed...\n";
}
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
var msg = String.Format("Some work completed in {0} ms.\n", milliseconds);
textBox1.Text += msg;
}
Private Async Sub threadExampleBtn_Click(sender As Object, e As RoutedEventArgs) Handles threadExampleBtn.Click
textBox1.Text = String.Empty
textBox1.Text = "Simulating work on UI thread." + vbCrLf
DoSomeWork(20)
textBox1.Text += "Work completed..." + vbCrLf
textBox1.Text += "Simulating work on non-UI thread." + vbCrLf
Await Task.Factory.StartNew(Sub()
DoSomeWork(1000)
End Sub)
textBox1.Text += "Work completed..." + vbCrLf
End Sub
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim msg = String.Format("Some work completed in {0} ms.", milliseconds) + vbCrLf
textBox1.Text += msg
End Sub
A versão a seguir do DoSomeWork
método elimina a exceção em um aplicativo do WPF.The following version of the DoSomeWork
method eliminates the exception in a WPF app.
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
bool uiAccess = textBox1.Dispatcher.CheckAccess();
String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
milliseconds, uiAccess ? String.Empty : "non-");
if (uiAccess)
textBox1.Text += msg;
else
textBox1.Dispatcher.Invoke(() => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.CheckAccess()
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread",
milliseconds, If(uiAccess, String.Empty, "non-")) +
vbCrLf
If uiAccess Then
textBox1.Text += msg
Else
textBox1.Dispatcher.Invoke( Sub() textBox1.Text += msg)
End If
End Sub
A versão a seguir do DoSomeWork
método elimina a exceção em um aplicativo UWP.The following version of the DoSomeWork
method eliminates the exception in a UWP app.
private async void DoSomeWork(int milliseconds)
{
// Simulate work.
await Task.Delay(milliseconds);
// Report completion.
bool uiAccess = textBox1.Dispatcher.HasThreadAccess;
String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
milliseconds, uiAccess ? String.Empty : "non-");
if (uiAccess)
textBox1.Text += msg;
else
await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { textBox1.Text += msg; });
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiAccess As Boolean = textBox1.Dispatcher.HasThreadAccess
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
milliseconds, If(uiAccess, String.Empty, "non-"))
If (uiAccess) Then
textBox1.Text += msg
Else
Await textBox1.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() textBox1.Text += msg)
End If
End Sub
Aplicativos do Windows FormsWindows Forms apps
List<String> lines = new List<String>();
private async void threadExampleBtn_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
lines.Clear();
lines.Add("Simulating work on UI thread.");
textBox1.Lines = lines.ToArray();
DoSomeWork(20);
lines.Add("Simulating work on non-UI thread.");
textBox1.Lines = lines.ToArray();
await Task.Run(() => DoSomeWork(1000));
lines.Add("ThreadsExampleBtn_Click completes. ");
textBox1.Lines = lines.ToArray();
}
private async void DoSomeWork(int milliseconds)
{
// simulate work
await Task.Delay(milliseconds);
// report completion
lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds));
textBox1.Lines = lines.ToArray();
}
Dim lines As New List(Of String)()
Private Async Sub threadExampleBtn_Click(sender As Object, e As EventArgs) Handles threadExampleBtn.Click
textBox1.Text = String.Empty
lines.Clear()
lines.Add("Simulating work on UI thread.")
textBox1.Lines = lines.ToArray()
DoSomeWork(20)
lines.Add("Simulating work on non-UI thread.")
textBox1.Lines = lines.ToArray()
Await Task.Run(Sub() DoSomeWork(1000))
lines.Add("ThreadsExampleBtn_Click completes. ")
textBox1.Lines = lines.ToArray()
End Sub
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds))
textBox1.Lines = lines.ToArray()
End Sub
A versão a seguir do DoSomeWork
método elimina a exceção em um aplicativo Windows Forms.The following version of the DoSomeWork
method eliminates the exception in a Windows Forms app.
private async void DoSomeWork(int milliseconds)
{
// simulate work
await Task.Delay(milliseconds);
// Report completion.
bool uiMarshal = textBox1.InvokeRequired;
String msg = String.Format("Some work completed in {0} ms. on {1}UI thread\n",
milliseconds, uiMarshal ? String.Empty : "non-");
lines.Add(msg);
if (uiMarshal) {
textBox1.Invoke(new Action(() => { textBox1.Lines = lines.ToArray(); }));
}
else {
textBox1.Lines = lines.ToArray();
}
}
Private Async Sub DoSomeWork(milliseconds As Integer)
' Simulate work.
Await Task.Delay(milliseconds)
' Report completion.
Dim uiMarshal As Boolean = textBox1.InvokeRequired
Dim msg As String = String.Format("Some work completed in {0} ms. on {1}UI thread" + vbCrLf,
milliseconds, If(uiMarshal, String.Empty, "non-"))
lines.Add(msg)
If uiMarshal Then
textBox1.Invoke(New Action(Sub() textBox1.Lines = lines.ToArray()))
Else
textBox1.Lines = lines.ToArray()
End If
End Sub
Alterando uma coleção ao iterarChanging a collection while iterating it
A foreach
instrução em C# ou For Each
instrução em Visual Basic é usada para iterar os membros de uma coleção e ler ou modificar seus elementos individuais.The foreach
statement in C# or For Each
statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. No entanto, ele não pode ser usado para adicionar ou remover itens da coleção.However, it can't be used to add or remove items from the collection. Isso gera uma InvalidOperationException exceção com uma mensagem semelhante a "a coleção foi modificada; a operação de enumeração pode não ser executada. "Doing this throws an InvalidOperationException exception with a message that is similar to, " Collection was modified; enumeration operation may not execute. "
O exemplo a seguir itera uma coleção de inteiros que tenta adicionar o quadrado de cada inteiro à coleção.The following example iterates a collection of integers attempts to add the square of each integer to the collection. O exemplo lança um InvalidOperationException com a primeira chamada para o List<T>.Add método.The example throws an InvalidOperationException with the first call to the List<T>.Add method.
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
var numbers = new List<int>() { 1, 2, 3, 4, 5 };
foreach (var number in numbers) {
int square = (int) Math.Pow(number, 2);
Console.WriteLine("{0}^{1}", number, square);
Console.WriteLine("Adding {0} to the collection...\n", square);
numbers.Add(square);
}
}
}
// The example displays the following output:
// 1^1
// Adding 1 to the collection...
//
//
// Unhandled Exception: System.InvalidOperationException: Collection was modified;
// enumeration operation may not execute.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
// at Example.Main()
Imports System.Collections.Generic
Module Example
Public Sub Main()
Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } )
For Each number In numbers
Dim square As Integer = CInt(Math.Pow(number, 2))
Console.WriteLine("{0}^{1}", number, square)
Console.WriteLine("Adding {0} to the collection..." + vbCrLf,
square)
numbers.Add(square)
Next
End Sub
End Module
' The example displays the following output:
' 1^1
' Adding 1 to the collection...
'
'
' Unhandled Exception: System.InvalidOperationException: Collection was modified;
' enumeration operation may not execute.
' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
' at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
' at Example.Main()
Você pode eliminar a exceção de uma das duas maneiras, dependendo da lógica do aplicativo:You can eliminate the exception in one of two ways, depending on your application logic:
Se os elementos tiverem que ser adicionados à coleção durante a iteração, você poderá iterar por índice usando a
for
instrução em vez deforeach
ouFor Each
.If elements must be added to the collection while iterating it, you can iterate it by index using thefor
statement instead offoreach
orFor Each
. O exemplo a seguir usa a instrução for para adicionar o quadrado de números na coleção à coleção.The following example uses the for statement to add the square of numbers in the collection to the collection.using System; using System.Collections.Generic; public class Example { public static void Main() { var numbers = new List<int>() { 1, 2, 3, 4, 5 }; int upperBound = numbers.Count - 1; for (int ctr = 0; ctr <= upperBound; ctr++) { int square = (int) Math.Pow(numbers[ctr], 2); Console.WriteLine("{0}^{1}", numbers[ctr], square); Console.WriteLine("Adding {0} to the collection...\n", square); numbers.Add(square); } Console.WriteLine("Elements now in the collection: "); foreach (var number in numbers) Console.Write("{0} ", number); } } // The example displays the following output: // 1^1 // Adding 1 to the collection... // // 2^4 // Adding 4 to the collection... // // 3^9 // Adding 9 to the collection... // // 4^16 // Adding 16 to the collection... // // 5^25 // Adding 25 to the collection... // // Elements now in the collection: // 1 2 3 4 5 1 4 9 16 25
Imports System.Collections.Generic Module Example Public Sub Main() Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) Dim upperBound = numbers.Count - 1 For ctr As Integer = 0 To upperBound Dim square As Integer = CInt(Math.Pow(numbers(ctr), 2)) Console.WriteLine("{0}^{1}", numbers(ctr), square) Console.WriteLine("Adding {0} to the collection..." + vbCrLf, square) numbers.Add(square) Next Console.WriteLine("Elements now in the collection: ") For Each number In numbers Console.Write("{0} ", number) Next End Sub End Module ' The example displays the following output: ' 1^1 ' Adding 1 to the collection... ' ' 2^4 ' Adding 4 to the collection... ' ' 3^9 ' Adding 9 to the collection... ' ' 4^16 ' Adding 16 to the collection... ' ' 5^25 ' Adding 25 to the collection... ' ' Elements now in the collection: ' 1 2 3 4 5 1 4 9 16 25
Observe que você deve estabelecer o número de iterações antes de iterar a coleção usando um contador dentro do loop que sairá do loop adequadamente, iterando retroativamente, de
Count
-1 para 0 ou, como faz o exemplo, atribuindo o número de elementos na matriz a uma variável e usando-o para estabelecer o limite superior do loop.Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropriately, by iterating backward, fromCount
- 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. Caso contrário, se um elemento for adicionado à coleção em cada iteração, os resultados de loop infinito.Otherwise, if an element is added to the collection on every iteration, an endless loop results.Se não for necessário adicionar elementos à coleção ao iterar, você poderá armazenar os elementos a serem adicionados em uma coleção temporária que você adicionar ao fazer a iteração da coleção.If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. O exemplo a seguir usa essa abordagem para adicionar o quadrado de números em uma coleção a uma coleção temporária e, em seguida, combinar as coleções em um único objeto de matriz.The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object.
using System; using System.Collections.Generic; public class Example { public static void Main() { var numbers = new List<int>() { 1, 2, 3, 4, 5 }; var temp = new List<int>(); // Square each number and store it in a temporary collection. foreach (var number in numbers) { int square = (int) Math.Pow(number, 2); temp.Add(square); } // Combine the numbers into a single array. int[] combined = new int[numbers.Count + temp.Count]; Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count); Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count); // Iterate the array. foreach (var value in combined) Console.Write("{0} ", value); } } // The example displays the following output: // 1 2 3 4 5 1 4 9 16 25
Imports System.Collections.Generic Module Example Public Sub Main() Dim numbers As New List(Of Integer)( { 1, 2, 3, 4, 5 } ) Dim temp As New List(Of Integer)() ' Square each number and store it in a temporary collection. For Each number In numbers Dim square As Integer = CInt(Math.Pow(number, 2)) temp.Add(square) Next ' Combine the numbers into a single array. Dim combined(numbers.Count + temp.Count - 1) As Integer Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count) Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count) ' Iterate the array. For Each value In combined Console.Write("{0} ", value) Next End Sub End Module ' The example displays the following output: ' 1 2 3 4 5 1 4 9 16 25
Classificando uma matriz ou coleção cujos objetos não podem ser comparadosSorting an array or collection whose objects cannot be compared
Os métodos de classificação de uso geral, como o Array.Sort(Array) método ou o List<T>.Sort() método, geralmente exigem que pelo menos um dos objetos a serem classificados implemente a IComparable<T> interface ou IComparable .General-purpose sorting methods, such as the Array.Sort(Array) method or the List<T>.Sort() method, usually require that at least one of the objects to be sorted implement the IComparable<T> or the IComparable interface. Caso contrário, a coleção ou a matriz não pode ser classificada, e o método gera uma InvalidOperationException exceção.If not, the collection or array cannot be sorted, and the method throws an InvalidOperationException exception. O exemplo a seguir define uma Person
classe, armazena dois Person
objetos em um List<T> objeto genérico e tenta classificá-los.The following example defines a Person
class, stores two Person
objects in a generic List<T> object, and attempts to sort them. Como a saída do exemplo mostra, a chamada para o List<T>.Sort() método gera um InvalidOperationException .As the output from the example shows, the call to the List<T>.Sort() method throws an InvalidOperationException.
using System;
using System.Collections.Generic;
public class Person
{
public Person(String fName, String lName)
{
FirstName = fName;
LastName = lName;
}
public String FirstName { get; set; }
public String LastName { get; set; }
}
public class Example
{
public static void Main()
{
var people = new List<Person>();
people.Add(new Person("John", "Doe"));
people.Add(new Person("Jane", "Doe"));
people.Sort();
foreach (var person in people)
Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
// System.ArgumentException: At least one object must implement IComparable.
// at System.Collections.Comparer.Compare(Object a, Object b)
// at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
// at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// --- End of inner exception stack trace ---
// at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
// at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
// at Example.Main()
Imports System.Collections.Generic
Public Class Person
Public Sub New(fName As String, lName As String)
FirstName = fName
LastName = lName
End Sub
Public Property FirstName As String
Public Property LastName As String
End Class
Module Example
Public Sub Main()
Dim people As New List(Of Person)()
people.Add(New Person("John", "Doe"))
people.Add(New Person("Jane", "Doe"))
people.Sort()
For Each person In people
Console.WriteLine("{0} {1}", person.FirstName, person.LastName)
Next
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException: Failed to compare two elements in the array. --->
' System.ArgumentException: At least one object must implement IComparable.
' at System.Collections.Comparer.Compare(Object a, Object b)
' at System.Collections.Generic.ArraySortHelper`1.SwapIfGreater(T[] keys, IComparer`1 comparer, Int32 a, Int32 b)
' at System.Collections.Generic.ArraySortHelper`1.DepthLimitedQuickSort(T[] keys, Int32 left, Int32 right, IComparer`1 comparer, Int32 depthLimit)
' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
' --- End of inner exception stack trace ---
' at System.Collections.Generic.ArraySortHelper`1.Sort(T[] keys, Int32 index, Int32 length, IComparer`1 comparer)
' at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer`1 comparer)
' at System.Collections.Generic.List`1.Sort(Int32 index, Int32 count, IComparer`1 comparer)
' at Example.Main()
Você pode eliminar a exceção de uma das três maneiras:You can eliminate the exception in any of three ways:
Se você puder ter o tipo que está tentando classificar (ou seja, se você controlar seu código-fonte), poderá modificá-lo para implementar a IComparable<T> IComparable interface ou.If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the IComparable<T> or the IComparable interface. Isso requer que você implemente o IComparable<T>.CompareTo ou o CompareTo método.This requires that you implement either the IComparable<T>.CompareTo or the CompareTo method. A adição de uma implementação de interface a um tipo existente não é uma alteração significativa.Adding an interface implementation to an existing type is not a breaking change.
O exemplo a seguir usa essa abordagem para fornecer uma IComparable<T> implementação para a
Person
classe.The following example uses this approach to provide an IComparable<T> implementation for thePerson
class. Você ainda pode chamar o método de classificação geral da coleção ou da matriz e, como a saída do exemplo mostra, a coleção é classificada com êxito.You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully.using System; using System.Collections.Generic; public class Person : IComparable<Person> { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } public int CompareTo(Person other) { return String.Format("{0} {1}", LastName, FirstName). CompareTo(String.Format("{0} {1}", 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
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
Se você não puder modificar o código-fonte do tipo que está tentando classificar, poderá definir uma classe de classificação de finalidade especial que implementa a IComparer<T> interface.If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the IComparer<T> interface. Você pode chamar uma sobrecarga do
Sort
método que inclui um IComparer<T> parâmetro.You can call an overload of theSort
method that includes an IComparer<T> parameter. Essa abordagem é especialmente útil se você quiser desenvolver uma classe de classificação especializada que possa classificar objetos com base em vários critérios.This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria.O exemplo a seguir usa a abordagem desenvolvendo uma
PersonComparer
classe personalizada que é usada para classificarPerson
coleções.The following example uses the approach by developing a customPersonComparer
class that is used to sortPerson
collections. Em seguida, ele passa uma instância dessa classe para o List<T>.Sort(IComparer<T>) método.It then passes an instance of this class to the List<T>.Sort(IComparer<T>) method.using System; using System.Collections.Generic; public class Person { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } } public class PersonComparer : IComparer<Person> { public int Compare(Person x, Person y) { return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("Jane", "Doe")); people.Sort(new PersonComparer()); foreach (var person in people) Console.WriteLine("{0} {1}", person.FirstName, person.LastName); } } // The example displays the following output: // Jane Doe // John Doe
Imports System.Collections.Generic Public Class Person Public Sub New(fName As String, lName As String) FirstName = fName LastName = lName End Sub Public Property FirstName As String Public Property LastName As String End Class Public Class PersonComparer : Implements IComparer(Of Person) Public Function Compare(x As Person, y As Person) As Integer _ Implements IComparer(Of Person).Compare Return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) End Function End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("Jane", "Doe")) people.Sort(New PersonComparer()) For Each person In people Console.WriteLine("{0} {1}", person.FirstName, person.LastName) Next End Sub End Module ' The example displays the following output: ' Jane Doe ' John Doe
Se você não puder modificar o código-fonte do tipo que está tentando classificar, poderá criar um Comparison<T> delegado para executar a classificação.If you cannot modify the source code for the type you are trying to sort, you can create a Comparison<T> delegate to perform the sorting. A assinatura delegada éThe delegate signature is
Function Comparison(Of T)(x As T, y As T) As Integer
int Comparison<T>(T x, T y)
O exemplo a seguir usa a abordagem definindo um
PersonComparison
método que corresponde à Comparison<T> assinatura delegada.The following example uses the approach by defining aPersonComparison
method that matches the Comparison<T> delegate signature. Em seguida, ele passa esse delegado para o List<T>.Sort(Comparison<T>) método.It then passes this delegate to the List<T>.Sort(Comparison<T>) method.using System; using System.Collections.Generic; public class Person { public Person(String fName, String lName) { FirstName = fName; LastName = lName; } public String FirstName { get; set; } public String LastName { get; set; } } public class Example { public static void Main() { var people = new List<Person>(); people.Add(new Person("John", "Doe")); people.Add(new Person("Jane", "Doe")); people.Sort(PersonComparison); foreach (var person in people) Console.WriteLine("{0} {1}", person.FirstName, person.LastName); } public static int PersonComparison(Person x, Person y) { return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)); } } // The example displays the following output: // Jane Doe // John Doe
Imports System.Collections.Generic Public Class Person Public Sub New(fName As String, lName As String) FirstName = fName LastName = lName End Sub Public Property FirstName As String Public Property LastName As String End Class Module Example Public Sub Main() Dim people As New List(Of Person)() people.Add(New Person("John", "Doe")) people.Add(New Person("Jane", "Doe")) people.Sort(AddressOf PersonComparison) For Each person In people Console.WriteLine("{0} {1}", person.FirstName, person.LastName) Next End Sub Public Function PersonComparison(x As Person, y As Person) As Integer Return String.Format("{0} {1}", x.LastName, x.FirstName). CompareTo(String.Format("{0} {1}", y.LastName, y.FirstName)) End Function End Module ' The example displays the following output: ' Jane Doe ' John Doe
Conversão de uma Anulável <T> que é nula para seu tipo subjacenteCasting a Nullable<T> that is null to its underlying type
Tentar converter um Nullable<T> valor que é null
para seu tipo subjacente gera uma InvalidOperationException exceção e exibe a mensagem de erro "o objeto anulável deve ter um valor.Attempting to cast a Nullable<T> value that is null
to its underlying type throws an InvalidOperationException exception and displays the error message, " Nullable object must have a value.
O exemplo a seguir gera uma InvalidOperationException exceção ao tentar iterar uma matriz que inclui um Nullable(Of Integer)
valor.The following example throws an InvalidOperationException exception when it attempts to iterate an array that includes a Nullable(Of Integer)
value.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
var queryResult = new int?[] { 1, 2, null, 4 };
var map = queryResult.Select(nullableInt => (int)nullableInt);
// Display list.
foreach (var num in map)
Console.Write("{0} ", num);
Console.WriteLine();
}
}
// The example displays the following output:
// 1 2
// Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
// at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
// at Example.<Main>b__0(Nullable`1 nullableInt)
// at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
// at Example.Main()
Imports System.Linq
Module Example
Public Sub Main()
Dim queryResult = New Integer?() { 1, 2, Nothing, 4 }
Dim map = queryResult.Select(Function(nullableInt) CInt(nullableInt))
' Display list.
For Each num In map
Console.Write("{0} ", num)
Next
Console.WriteLine()
End Sub
End Module
' The example displays thIe following output:
' 1 2
' Unhandled Exception: System.InvalidOperationException: Nullable object must have a value.
' at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
' at Example.<Main>b__0(Nullable`1 nullableInt)
' at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
' at Example.Main()
Para evitar a exceção:To prevent the exception:
Use a Nullable<T>.HasValue propriedade para selecionar apenas os elementos que não são
null
.Use the Nullable<T>.HasValue property to select only those elements that are notnull
.Chame uma das Nullable<T>.GetValueOrDefault sobrecargas para fornecer um valor padrão para um
null
valor.Call one of the Nullable<T>.GetValueOrDefault overloads to provide a default value for anull
value.
O exemplo a seguir faz ambos para evitar a InvalidOperationException exceção.The following example does both to avoid the InvalidOperationException exception.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
var queryResult = new int?[] { 1, 2, null, 4 };
var numbers = queryResult.Select(nullableInt => (int)nullableInt.GetValueOrDefault());
// Display list using Nullable<int>.HasValue.
foreach (var number in numbers)
Console.Write("{0} ", number);
Console.WriteLine();
numbers = queryResult.Select(nullableInt => (int) (nullableInt.HasValue ? nullableInt : -1));
// Display list using Nullable<int>.GetValueOrDefault.
foreach (var number in numbers)
Console.Write("{0} ", number);
Console.WriteLine();
}
}
// The example displays the following output:
// 1 2 0 4
// 1 2 -1 4
Imports System.Linq
Module Example
Public Sub Main()
Dim queryResult = New Integer?() { 1, 2, Nothing, 4 }
Dim numbers = queryResult.Select(Function(nullableInt) _
CInt(nullableInt.GetValueOrDefault()))
' Display list.
For Each number In numbers
Console.Write("{0} ", number)
Next
Console.WriteLine()
' Use -1 to indicate a missing values.
numbers = queryResult.Select(Function(nullableInt) _
CInt(If(nullableInt.HasValue, nullableInt, -1)))
' Display list.
For Each number In numbers
Console.Write("{0} ", number)
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' 1 2 0 4
' 1 2 -1 4
Chamando um método System. Linq. Enumerable em uma coleção vaziaCalling a System.Linq.Enumerable method on an empty collection
Os Enumerable.Aggregate métodos,,,,,, Enumerable.Average Enumerable.First Enumerable.Last Enumerable.Max Enumerable.Min Enumerable.Single e Enumerable.SingleOrDefault executam operações em uma sequência e retornam um único resultado.The Enumerable.Aggregate, Enumerable.Average, Enumerable.First, Enumerable.Last, Enumerable.Max, Enumerable.Min, Enumerable.Single, and Enumerable.SingleOrDefault methods perform operations on a sequence and return a single result. Algumas sobrecargas desses métodos geram uma InvalidOperationException exceção quando a sequência está vazia, enquanto outras sobrecargas retornam null
.Some overloads of these methods throw an InvalidOperationException exception when the sequence is empty, while other overloads return null
. O Enumerable.SingleOrDefault método também gera uma InvalidOperationException exceção quando a sequência contém mais de um elemento.The Enumerable.SingleOrDefault method also throws an InvalidOperationException exception when the sequence contains more than one element.
Observação
A maioria dos métodos que geram uma InvalidOperationException exceção são sobrecargas.Most of the methods that throw an InvalidOperationException exception are overloads. Certifique-se de entender o comportamento da sobrecarga que você escolher.Be sure that you understand the behavior of the overload that you choose.
A tabela a seguir lista as mensagens de exceção dos InvalidOperationException objetos de exceção lançados por chamadas para alguns System.Linq.Enumerable métodos.The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to some System.Linq.Enumerable methods.
MétodoMethod | MensagemMessage |
---|---|
Aggregate Average Last Max Min |
A sequência não contém elementosSequence contains no elements |
First |
A sequência não contém nenhum elemento correspondenteSequence contains no matching element |
Single SingleOrDefault |
A sequência contém mais de um elemento correspondenteSequence contains more than one matching element |
A forma como você elimina ou manipula a exceção depende das suposições do seu aplicativo e do método específico que você chama.How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call.
Ao chamar deliberadamente um desses métodos sem verificar uma sequência vazia, você está supondo que a sequência não está vazia e que uma sequência vazia é uma ocorrência inesperada.When you deliberately call one of these methods without checking for an empty sequence, you are assuming that the sequence is not empty, and that an empty sequence is an unexpected occurrence. Nesse caso, é apropriado capturar ou relançar a exceção.In this case, catching or rethrowing the exception is appropriate .
Se a sua falha de verificação de uma sequência vazia for inadvertida, você poderá chamar uma das sobrecargas da Enumerable.Any sobrecarga para determinar se uma sequência contém elementos.If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the Enumerable.Any overload to determine whether a sequence contains any elements.
Dica
Chamar o Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) método antes de gerar uma sequência pode melhorar o desempenho se os dados a serem processados puderem conter um grande número de elementos ou se a operação que gera a sequência for cara.Calling the Enumerable.Any<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive.
Se você tiver chamado um método como, Enumerable.First Enumerable.Last ou, Enumerable.Single você pode substituir um método alternativo, como Enumerable.FirstOrDefault , Enumerable.LastOrDefault ou Enumerable.SingleOrDefault , que retorna um valor padrão em vez de um membro da sequência.If you've called a method such as Enumerable.First, Enumerable.Last, or Enumerable.Single, you can substitute an alternate method, such as Enumerable.FirstOrDefault, Enumerable.LastOrDefault, or Enumerable.SingleOrDefault, that returns a default value instead of a member of the sequence.
Os exemplos fornecem detalhes adicionais.The examples provide additional detail.
O exemplo a seguir usa o Enumerable.Average método para calcular a média de uma sequência cujos valores são maiores que 4.The following example uses the Enumerable.Average method to compute the average of a sequence whose values are greater than 4. Como nenhum valor da matriz original excede 4, nenhum valor é incluído na sequência e o método gera uma InvalidOperationException exceção.Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an InvalidOperationException exception.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] data = { 1, 2, 3, 4 };
var average = data.Where(num => num > 4).Average();
Console.Write("The average of numbers greater than 4 is {0}",
average);
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
// at System.Linq.Enumerable.Average(IEnumerable`1 source)
// at Example.Main()
Imports System.Linq
Module Example
Public Sub Main()
Dim data() As Integer = { 1, 2, 3, 4 }
Dim average = data.Where(Function(num) num > 4).Average()
Console.Write("The average of numbers greater than 4 is {0}",
average)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
' at System.Linq.Enumerable.Average(IEnumerable`1 source)
' at Example.Main()
A exceção pode ser eliminada chamando o Any método para determinar se a sequência contém elementos antes de chamar o método que processa a sequência, como mostra o exemplo a seguir.The exception can be eliminated by calling the Any method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var moreThan4 = dbQueryResults.Where(num => num > 4);
if(moreThan4.Any())
Console.WriteLine("Average value of numbers greater than 4: {0}:",
moreThan4.Average());
else
// handle empty collection
Console.WriteLine("The dataset has no values greater than 4.");
}
}
// The example displays the following output:
// The dataset has no values greater than 4.
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim moreThan4 = dbQueryResults.Where(Function(num) num > 4)
If moreThan4.Any() Then
Console.WriteLine("Average value of numbers greater than 4: {0}:",
moreThan4.Average())
Else
' Handle empty collection.
Console.WriteLine("The dataset has no values greater than 4.")
End If
End Sub
End Module
' The example displays the following output:
' The dataset has no values greater than 4.
O Enumerable.First método retorna o primeiro item em uma sequência ou o primeiro elemento em uma sequência que satisfaça uma condição especificada.The Enumerable.First method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. Se a sequência estiver vazia e, portanto, não tiver um primeiro elemento, ele lançará uma InvalidOperationException exceção.If the sequence is empty and therefore does not have a first element, it throws an InvalidOperationException exception.
No exemplo a seguir, o Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) método gera uma InvalidOperationException exceção porque a matriz dbQueryResults não contém um elemento maior que 4.In the following example, the Enumerable.First<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method throws an InvalidOperationException exception because the dbQueryResults array doesn't contain an element greater than 4.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var firstNum = dbQueryResults.First(n => n > 4);
Console.WriteLine("The first value greater than 4 is {0}",
firstNum);
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains no matching element
// at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
// at Example.Main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim firstNum = dbQueryResults.First(Function(n) n > 4)
Console.WriteLine("The first value greater than 4 is {0}",
firstNum)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains no matching element
' at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
Você pode chamar o Enumerable.FirstOrDefault método em vez de Enumerable.First para retornar um valor padrão ou especificado.You can call the Enumerable.FirstOrDefault method instead of Enumerable.First to return a specified or default value. Se o método não encontrar um primeiro elemento na sequência, ele retornará o valor padrão para esse tipo de dados.If the method does not find a first element in the sequence, it returns the default value for that data type. O valor padrão é null
para um tipo de referência, zero para um tipo de dados numérico e DateTime.MinValue para o DateTime tipo.The default value is null
for a reference type, zero for a numeric data type, and DateTime.MinValue for the DateTime type.
Observação
A interpretação do valor retornado pelo Enumerable.FirstOrDefault método é geralmente complicada pelo fato de que o valor padrão do tipo pode ser um valor válido na sequência.Interpreting the value returned by the Enumerable.FirstOrDefault method is often complicated by the fact that the default value of the type can be a valid value in the sequence. Nesse caso, você deve chamar o Enumerable.Any método para determinar se a sequência tem membros válidos antes de chamar o Enumerable.First método.In this case, you an call the Enumerable.Any method to determine whether the sequence has valid members before calling the Enumerable.First method.
O exemplo a seguir chama o Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) método para evitar a InvalidOperationException exceção lançada no exemplo anterior.The following example calls the Enumerable.FirstOrDefault<TSource>(IEnumerable<TSource>, Func<TSource,Boolean>) method to prevent the InvalidOperationException exception thrown in the previous example.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var firstNum = dbQueryResults.FirstOrDefault(n => n > 4);
if (firstNum == 0)
Console.WriteLine("No value is greater than 4.");
else
Console.WriteLine("The first value greater than 4 is {0}",
firstNum);
}
}
// The example displays the following output:
// No value is greater than 4.
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim firstNum = dbQueryResults.FirstOrDefault(Function(n) n > 4)
If firstNum = 0 Then
Console.WriteLIne("No value is greater than 4.")
Else
Console.WriteLine("The first value greater than 4 is {0}",
firstNum)
End If
End Sub
End Module
' The example displays the following output:
' No value is greater than 4.
Chamando Enumerable. single ou Enumerable. SingleOrDefault em uma sequência sem um elementoCalling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
O Enumerable.Single método retorna o único elemento de uma sequência ou o único elemento de uma sequência que atende a uma condição especificada.The Enumerable.Single method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. Se não houver elementos na sequência, ou se houver mais de um elemento, o método lançará uma InvalidOperationException exceção.If there are no elements in the sequence, or if there is more than one element , the method throws an InvalidOperationException exception.
Você pode usar o Enumerable.SingleOrDefault método para retornar um valor padrão em vez de lançar uma exceção quando a sequência não contiver elementos.You can use the Enumerable.SingleOrDefault method to return a default value instead of throwing an exception when the sequence contains no elements. No entanto, o Enumerable.SingleOrDefault método ainda gera uma InvalidOperationException exceção quando a sequência contém mais de um elemento.However, the Enumerable.SingleOrDefault method still throws an InvalidOperationException exception when the sequence contains more than one element.
A tabela a seguir lista as mensagens de exceção dos InvalidOperationException objetos de exceção lançados por chamadas para os Enumerable.Single Enumerable.SingleOrDefault métodos e.The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to the Enumerable.Single and Enumerable.SingleOrDefault methods.
MétodoMethod | MensagemMessage |
---|---|
Single |
A sequência não contém nenhum elemento correspondenteSequence contains no matching element |
Single SingleOrDefault |
A sequência contém mais de um elemento correspondenteSequence contains more than one matching element |
No exemplo a seguir, a chamada para o Enumerable.Single método gera uma InvalidOperationException exceção porque a sequência não tem um elemento maior que 4.In the following example, the call to the Enumerable.Single method throws an InvalidOperationException exception because the sequence doesn't have an element greater than 4.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var singleObject = dbQueryResults.Single(value => value > 4);
// Display results.
Console.WriteLine("{0} is the only value greater than 4", singleObject);
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains no matching element
// at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
// at Example.Main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim singleObject = dbQueryResults.Single(Function(value) value > 4)
' Display results.
Console.WriteLine("{0} is the only value greater than 4",
singleObject)
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains no matching element
' at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
O exemplo a seguir tenta impedir que a InvalidOperationException exceção seja gerada quando uma sequência está vazia, chamando o Enumerable.SingleOrDefault método.The following example attempts to prevent the InvalidOperationException exception thrown when a sequence is empty by instead calling the Enumerable.SingleOrDefault method. No entanto, como essa sequência retorna vários elementos cujo valor é maior que 2, ele também gera uma InvalidOperationException exceção.However, because this sequence returns multiple elements whose value is greater than 2, it also throws an InvalidOperationException exception.
using System;
using System.Linq;
public class Example
{
public static void Main()
{
int[] dbQueryResults = { 1, 2, 3, 4 };
var singleObject = dbQueryResults.SingleOrDefault(value => value > 2);
if (singleObject != 0)
Console.WriteLine("{0} is the only value greater than 2",
singleObject);
else
// Handle an empty collection.
Console.WriteLine("No value is greater than 2");
}
}
// The example displays the following output:
// Unhandled Exception: System.InvalidOperationException:
// Sequence contains more than one matching element
// at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
// at Example.Main()
Imports System.Linq
Module Example
Public Sub Main()
Dim dbQueryResults() As Integer = { 1, 2, 3, 4 }
Dim singleObject = dbQueryResults.SingleOrDefault(Function(value) value > 2)
If singleObject <> 0 Then
Console.WriteLine("{0} is the only value greater than 2",
singleObject)
Else
' Handle an empty collection.
Console.WriteLine("No value is greater than 2")
End If
End Sub
End Module
' The example displays the following output:
' Unhandled Exception: System.InvalidOperationException:
' Sequence contains more than one matching element
' at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
' at Example.Main()
Chamar o Enumerable.Single método pressupõe que uma sequência ou a sequência que atende aos critérios especificados contém apenas um elemento.Calling the Enumerable.Single method assumes that either a sequence or the sequence that meets specified criteria contains only one element. Enumerable.SingleOrDefault assume uma sequência com zero ou um resultado, mas não mais.Enumerable.SingleOrDefault assumes a sequence with zero or one result, but no more. Se essa suposição for uma deliberada de sua parte e essas condições não forem atendidas, a regeração ou a captura do resultado InvalidOperationException será apropriada.If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting InvalidOperationException is appropriate. Caso contrário, ou se você esperar que condições inválidas ocorram com alguma frequência, considere usar algum outro Enumerable método, como FirstOrDefault ou Where .Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other Enumerable method, such as FirstOrDefault or Where.
Acesso dinâmico ao campo de domínio entre aplicativosDynamic cross-application domain field access
A OpCodes.Ldflda instrução Microsoft Intermediate Language (MSIL) gera uma InvalidOperationException exceção se o objeto que contém o campo cujo endereço você está tentando recuperar não está dentro do domínio do aplicativo no qual seu código está sendo executado.The OpCodes.Ldflda Microsoft intermediate language (MSIL) instruction throws an InvalidOperationException exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. O endereço de um campo só pode ser acessado do domínio do aplicativo no qual ele reside.The address of a field can only be accessed from the application domain in which it resides.
Gerando uma exceção InvalidOperationExceptionThrowing an InvalidOperationException exception
Você deve lançar uma InvalidOperationException exceção somente quando o estado do seu objeto por algum motivo não oferecer suporte a uma chamada de método específica.You should throw an InvalidOperationException exception only when the state of your object for some reason does not support a particular method call. Ou seja, a chamada do método é válida em algumas circunstâncias ou contextos, mas é inválida em outras.That is, the method call is valid in some circumstances or contexts, but is invalid in others.
Se a falha de invocação do método for devido a argumentos inválidos, ArgumentException ou uma de suas classes derivadas, ArgumentNullException ou ArgumentOutOfRangeException , deverá ser lançada em vez disso.If the method invocation failure is due to invalid arguments, then ArgumentException or one of its derived classes, ArgumentNullException or ArgumentOutOfRangeException, should be thrown instead.
Informações diversasMiscellaneous information
InvalidOperationException usa o COR_E_INVALIDOPERATION HRESULT, que tem o valor 0x80131509.InvalidOperationException uses the HRESULT COR_E_INVALIDOPERATION, which has the value 0x80131509.
Para obter uma lista de valores de propriedade inicial para uma instância do InvalidOperationException, consulte o InvalidOperationException construtores.For a list of initial property values for an instance of InvalidOperationException, see the InvalidOperationException constructors.
Construtores
InvalidOperationException() |
Inicializa uma nova instância da classe InvalidOperationException.Initializes a new instance of the InvalidOperationException class. |
InvalidOperationException(SerializationInfo, StreamingContext) |
Inicializa uma nova instância da classe InvalidOperationException com dados serializados.Initializes a new instance of the InvalidOperationException class with serialized data. |
InvalidOperationException(String) |
Inicializa uma nova instância da classe InvalidOperationException com uma mensagem de erro especificada.Initializes a new instance of the InvalidOperationException class with a specified error message. |
InvalidOperationException(String, Exception) |
Inicializa uma nova instância da classe InvalidOperationException com uma mensagem de erro especificada e uma referência à exceção interna que é a causa da exceção.Initializes a new instance of the InvalidOperationException class with a specified error message and a reference to the inner exception that is the cause of this exception. |
Propriedades
Data |
Obtém uma coleção de pares de chave/valor que fornecem informações definidas pelo usuário adicionais sobre a exceção.Gets a collection of key/value pairs that provide additional user-defined information about the exception. (Herdado de Exception) |
HelpLink |
Obtém ou define um link para o arquivo de ajuda associado a essa exceção.Gets or sets a link to the help file associated with this exception. (Herdado de Exception) |
HResult |
Obtém ou define HRESULT, um valor numérico codificado que é atribuído a uma exceção específica.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Herdado de Exception) |
InnerException |
Obtém a instância Exception que causou a exceção atual.Gets the Exception instance that caused the current exception. (Herdado de Exception) |
Message |
Obtém uma mensagem que descreve a exceção atual.Gets a message that describes the current exception. (Herdado de Exception) |
Source |
Obtém ou define o nome do aplicativo ou objeto que causa o erro.Gets or sets the name of the application or the object that causes the error. (Herdado de Exception) |
StackTrace |
Obtém uma representação de cadeia de caracteres de quadros imediatos na pilha de chamadas.Gets a string representation of the immediate frames on the call stack. (Herdado de Exception) |
TargetSite |
Obtém o método que gerou a exceção atual.Gets the method that throws the current exception. (Herdado de Exception) |
Métodos
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
GetBaseException() |
Quando substituído em uma classe derivada, retorna a Exception que é a causa raiz de uma ou mais exceções subsequentes.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Herdado de Exception) |
GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
GetObjectData(SerializationInfo, StreamingContext) |
Quando substituído em uma classe derivada, define o SerializationInfo com informações sobre a exceção.When overridden in a derived class, sets the SerializationInfo with information about the exception. (Herdado de Exception) |
GetType() |
Obtém o tipo de runtime da instância atual.Gets the runtime type of the current instance. (Herdado de Exception) |
MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
ToString() |
Cria e retorna uma representação de cadeia de caracteres da exceção atual.Creates and returns a string representation of the current exception. (Herdado de Exception) |
Eventos
SerializeObjectState |
Ocorre quando uma exceção é serializada para criar um objeto de estado de exceção que contém dados serializados sobre a exceção.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Herdado de Exception) |