Questo articolo è stato tradotto automaticamente. Per visualizzare l'articolo in inglese, selezionare la casella di controllo Inglese. È possibile anche visualizzare il testo inglese in una finestra popup posizionando il puntatore del mouse sopra il testo.
Traduzione
Inglese

Classe InvalidOperationException

 

Data di pubblicazione: ottobre 2016

Eccezione generata quando una chiamata a un metodo non è valida per lo stato corrente dell'oggetto.

Spazio dei nomi:   System
Assembly:  mscorlib (in mscorlib.dll)


[SerializableAttribute]
[ComVisibleAttribute(true)]
public class InvalidOperationException : SystemException

NomeDescrizione
System_CAPS_pubmethodInvalidOperationException()

Inizializza una nuova istanza della classe InvalidOperationException.

System_CAPS_protmethodInvalidOperationException(SerializationInfo, StreamingContext)

Inizializza una nuova istanza della classe InvalidOperationException con dati serializzati.

System_CAPS_pubmethodInvalidOperationException(String)

Inizializza una nuova istanza della classe InvalidOperationException con un messaggio di errore specificato.

System_CAPS_pubmethodInvalidOperationException(String, Exception)

Inizializza una nuova istanza della classe InvalidOperationException con un messaggio di errore specificato e un riferimento all'eccezione interna che è la causa dell'eccezione corrente.

NomeDescrizione
System_CAPS_pubpropertyData

Ottiene una collezione di coppie chiave/valore che forniscono ulteriori informazioni definite dall'utente sull'eccezione. (Ereditato da Exception.)

System_CAPS_pubpropertyHelpLink

Ottiene o imposta un collegamento al file della Guida associato all'eccezione.(Ereditato da Exception.)

System_CAPS_pubpropertyHResult

Ottiene o imposta HRESULT, un valore numerico codificato che viene assegnato ad una specifica eccezione. (Ereditato da Exception.)

System_CAPS_pubpropertyInnerException

Ottiene l'istanza di Exception che ha causato l'eccezione corrente.(Ereditato da Exception.)

System_CAPS_pubpropertyMessage

Ottiene un messaggio che descrive l'eccezione corrente.(Ereditato da Exception.)

System_CAPS_pubpropertySource

Ottiene o imposta il nome dell'oggetto o dell'applicazione che ha generato l'errore.(Ereditato da Exception.)

System_CAPS_pubpropertyStackTrace

Ottiene una rappresentazione in forma di stringa dei frame nello stack di chiamate. (Ereditato da Exception.)

System_CAPS_pubpropertyTargetSite

Ottiene il metodo che ha generato l'eccezione corrente. (Ereditato da Exception.)

NomeDescrizione
System_CAPS_pubmethodEquals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente. (Ereditato da Object.)

System_CAPS_protmethodFinalize()

Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che l'oggetto stesso venga reclamato dalla procedura di Garbage Collection. (Ereditato da Object.)

System_CAPS_pubmethodGetBaseException()

Quando ne viene eseguito l'override in una classe derivata, restituisce l'Exception che è la causa radice di una o più eccezioni successive.(Ereditato da Exception.)

System_CAPS_pubmethodGetHashCode()

Funge da funzione hash predefinita.(Ereditato da Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

Quando ne viene eseguito l'override in una classe derivata, imposta il controllo SerializationInfo con le informazioni sull'eccezione.(Ereditato da Exception.)

System_CAPS_pubmethodGetType()

Ottiene il tipo di runtime dell'istanza corrente.(Ereditato da Exception.)

System_CAPS_protmethodMemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.(Ereditato da Object.)

System_CAPS_pubmethodToString()

Crea e restituisce una rappresentazione di stringa dell'eccezione corrente.(Ereditato da Exception.)

NomeDescrizione
System_CAPS_proteventSerializeObjectState

Si verifica quando un'eccezione viene serializzata per creare un oggetto di stato eccezione contenente i dati serializzati relativi all'eccezione.(Ereditato da Exception.)

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it is thrown when the state of an object cannot support the method call. For example, an InvalidOperationException exception is thrown by methods such as:

System_CAPS_importantImportante

Because the T:System.InvalidOperationException exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the P:System.Exception.Message property.

In this section:

Some common causes of InvalidOperationException exceptions
      Updating a UI thread from a non-UI thread
      Changing a collection while iterating it
      Sorting an array or collection whose objects cannot be compared
      Casting a Nullable<T> that is null to its underlying type 
      Calling a System.Linq.Enumerable method on an empty collection
      Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
      Dynamic cross-application domain field access
Throwing an InvalidOperationException exception
Miscellaneous information

The following sections show how some common cases in which in T:System.InvalidOperationException exception is thrown in an app. How you handle the issue depends on the specific situation. Most commonly, however, the exception results from developer error, and the T:System.InvalidOperationException exception can be anticipated and avoided.

Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. However. 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). An T:System.InvalidOperationException is thrown when you try to access a UI element from a thread other than the UI thread. The text of the exception message is shown in the following table.

Application Type

Message

WPF app

The calling thread cannot access this object because a different thread owns it.

UWP app

The application called an interface that was marshalled for a different thread.

Windows Forms app

Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.

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:

  • In WPF apps, call the M:System.Windows.Threading.Dispatcher.CheckAccess method to determine if a method is running on a non-UI thread. It returns true if the method is running on the UI thread and false otherwise. Call one of the overloads of the M:System.Windows.Threading.Dispatcher.Invoke(System.Action) method to schedule the call on the UI thread.

  • In UWP apps, call the CoreDispatcher.HasThreadAccesshttps://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.hasthreadaccess.aspx method to determine if a method is running on a non-UI thread. Call the CoreDispatcher.RunAsynchttps://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.core.coredispatcher.runasync.aspx method to execute a delegate that updates the UI thread. Use the

  • In Windows Forms apps, use the P:System.Windows.Forms.Control.InvokeRequired property to determine if a method is running on a non-UI thread. Call one of the overloads of the M:System.Windows.Forms.Control.Invoke(System.Delegate) method to execute a delegate that updates the UI thread.

The following examples illustrate the T:System.InvalidOperationException exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Each example requires that you create two controls:

  • A text box control named textBox1. In a Windows Forms app, you should set its P:System.Windows.Forms.TextBox.Multiline property to true.

  • A button control named threadExampleBtn. The example provides a handler, ThreadsExampleBtn_Click, for the button's Click event.

In each case, the threadExampleBtn_Click event handler calls the DoSomeWork method twice. The first call runs synchronously and succeeds. But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. This results in a T:System.InvalidOperationException exception.

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

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

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

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

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

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; });
}

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; });
}
Windows Forms apps
List<String> lines = new List<String>();

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

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

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

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

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

    // report completion
    lines.Add(String.Format("Some work completed in {0} ms on UI thread.", milliseconds));
    textBox1.Lines = lines.ToArray();
}

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

The foreach statement in C# or For Each statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. However, it can't be used to add or remove items from the collection. Doing this throws an T:System.InvalidOperationException exception with a message that is similar to, "Collection was modified; enumeration operation may not execute."

The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an T:System.InvalidOperationException with the first call to the M:System.Collections.Generic.List`1.Add(`0) 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()

You can eliminate the exception in one of two ways, depending on your application logic:

  • If elements must be added to the collection while iterating it, you can iterate it by index using the for statement instead of foreach or For Each. 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
    

    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 appropraitely, by iterating backward, from Count - 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. Otherwise, if an element is added to the collection on every iteration, an endless loop results.

  • If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          var numbers = new List<int>() { 1, 2, 3, 4, 5 };
          var temp = new List<int>();
    
          // Square each number and store it in a temporary collection.
          foreach (var number in numbers) {
             int square = (int) Math.Pow(number, 2);
             temp.Add(square);
          }
    
          // Combine the numbers into a single array.
          int[] combined = new int[numbers.Count + temp.Count];
          Array.Copy(numbers.ToArray(), 0, combined, 0, numbers.Count);
          Array.Copy(temp.ToArray(), 0, combined, numbers.Count, temp.Count);
    
          // Iterate the array.
          foreach (var value in combined)
             Console.Write("{0}    ", value);
       }
    }
    // The example displays the following output:
    //       1    2    3    4    5    1    4    9    16    25
    

General-purpose sorting methods, such as the M:System.Array.Sort(System.Array) method or the M:System.Collections.Generic.List`1.Sort method, usually require that at least one of the objects to be sorted implement the T:System.IComparable`1 or the T:System.IComparable interface. If not, the collection or array cannot be sorted, and the method throws an T:System.InvalidOperationException exception. The following example defines a Person class, stores two Person objects in a generic T:System.Collections.Generic.List`1 object, and attempts to sort them. As the output from the example shows, the call to the M:System.Collections.Generic.List`1.Sort method throws an T:System.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()

You can eliminate the exception in any of three ways:

  • 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 T:System.IComparable`1 or the T:System.IComparable interface. This requires that you implement either the M:System.IComparable`1.CompareTo(`0) or the M:System.IComparable.CompareTo(System.Object) method. Adding an interface implementation to an existing type is not a breaking change.

    The following example uses this approach to provide an T:System.IComparable`1 implementation for the Person class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully.

    using System;
    using System.Collections.Generic;
    
    public class Person : IComparable<Person>
    {
       public Person(String fName, String lName)
       {
          FirstName = fName;
          LastName = lName;
       }
    
       public String FirstName { get; set; }
       public String LastName { get; set; }
    
       public int CompareTo(Person other)
       {
          return String.Format("{0} {1}", LastName, FirstName).
                 CompareTo(String.Format("{0} {1}", LastName, FirstName));    
       }       
    }
    
    public class Example
    {
       public static void Main()
       {
          var people = new List<Person>();
    
          people.Add(new Person("John", "Doe"));
          people.Add(new Person("Jane", "Doe"));
          people.Sort();
          foreach (var person in people)
             Console.WriteLine("{0} {1}", person.FirstName, person.LastName);
       }
    }
    // The example displays the following output:
    //       Jane Doe
    //       John Doe
    
  • 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 T:System.Collections.Generic.IComparer`1 interface. You can call an overload of the Sort method that includes an T:System.Collections.Generic.IComparer`1 parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria.

    The following example uses the approach by developing a custom PersonComparer class that is used to sort Person collections. It then passes an instance of this class to the M:System.Collections.Generic.List`1.Sort(System.Collections.Generic.IComparer{`0}) 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
    
  • If you cannot modify the source code for the type you are trying to sort, you can create a T:System.Comparison`1 delegate to perform the sorting. The delegate signature is

    int Comparison<T>(T x, T y)
    

    The following example uses the approach by defining a PersonComparison method that matches the T:System.Comparison`1 delegate signature. It then passes this delegate to the M:System.Collections.Generic.List`1.Sort(System.Comparison{`0}) 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
    

Attempting to cast a T:System.Nullable`1 value that is null to its underlying type throws an T:System.InvalidOperationException exception and displays the error message, "Nullable object must have a value.

The following example throws an T:System.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()

To prevent the exception:

  • Use the P:System.Nullable`1.HasValue property to select only those elements that are not null.

  • Call one of the M:System.Nullable`1.GetValueOrDefault overloads to provide a default value for a null value.

The following example does both to avoid the T:System.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

The M:System.Linq.Enumerable.Aggregate``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,``0,``0}), M:System.Linq.Enumerable.Average(System.Collections.Generic.IEnumerable{System.Decimal}), M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0}), M:System.Linq.Enumerable.Last``1(System.Collections.Generic.IEnumerable{``0}), M:System.Linq.Enumerable.Max(System.Collections.Generic.IEnumerable{System.Decimal}), M:System.Linq.Enumerable.Min(System.Collections.Generic.IEnumerable{System.Decimal}), M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}), and M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) methods perform operations on a sequence and return a single result. Some overloads of these methods throw an T:System.InvalidOperationException exception when the sequence is empty, while other overloads return null. The M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method also throws an T:System.InvalidOperationException exception when the sequence contains more than one element.

System_CAPS_noteNota

Most of the methods that throw an T:System.InvalidOperationException exception are overloads. Be sure that you understand the behavior of the overload that you choose.

The following table lists the exception messages from the T:System.InvalidOperationException exception objects thrown by calls to some T:System.Linq.Enumerable methods.

Method

Message

Aggregate
Average
Last
Max
Min

Sequence contains no elements

First

Sequence contains no matching element

Single
SingleOrDefault

Sequence contains more than one matching element

How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call.

  • 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. In this case, catching or rethrowing the exception is appropriate .

  • If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the M:System.Linq.Enumerable.Any``1(System.Collections.Generic.IEnumerable{``0}) overload to determine whether a sequence contains any elements.

    System_CAPS_tipSuggerimento

    Calling the M:System.Linq.Enumerable.Any``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.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.

  • If you've called a method such as M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0}), M:System.Linq.Enumerable.Last``1(System.Collections.Generic.IEnumerable{``0}), or M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}), you can substitute an alternate method, such as M:System.Linq.Enumerable.FirstOrDefault``1(System.Collections.Generic.IEnumerable{``0}), M:System.Linq.Enumerable.LastOrDefault``1(System.Collections.Generic.IEnumerable{``0}), or M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}), that returns a default value instead of a member of the sequence.

The examples provide additional detail.

The following example uses the M:System.Linq.Enumerable.Average(System.Collections.Generic.IEnumerable{System.Decimal}) method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an T:System.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()

The exception can be eliminated by calling the M:System.Linq.Enumerable.Any``1(System.Collections.Generic.IEnumerable{``0}) 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.

The M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0}) method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an T:System.InvalidOperationException exception.

In the following example, the M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.Boolean}) method throws an T:System.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()

You can call the M:System.Linq.Enumerable.FirstOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method instead of M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0}) to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is null for a reference type, zero for a numeric data type, and F:System.DateTime.MinValue for the T:System.DateTime type.

System_CAPS_noteNota

Interpreting the value returned by the M:System.Linq.Enumerable.FirstOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the M:System.Linq.Enumerable.Any``1(System.Collections.Generic.IEnumerable{``0})method to determine whether the sequence has valid members before calling the M:System.Linq.Enumerable.First``1(System.Collections.Generic.IEnumerable{``0}) method.

The following example calls the M:System.Linq.Enumerable.FirstOrDefault``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.Boolean}) method to prevent the T:System.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.

The M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}) method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an T:System.InvalidOperationException exception.

You can use the M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method to return a default value instead of throwing an exception when the sequence contains no elements. However, the M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method still throws an T:System.InvalidOperationException exception when the sequence contains more than one element.

The following table lists the exception messages from the T:System.InvalidOperationException exception objects thrown by calls to the M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}) and M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) methods.

Method

Message

Single

Sequence contains no matching element

Single
SingleOrDefault

Sequence contains more than one matching element

In the following example, the call to the M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}) method throws an T:System.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()

The following example attempts to prevent the T:System.InvalidOperationException exception thrown when a sequence is empty by instead calling the M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an T:System.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()

Calling the M:System.Linq.Enumerable.Single``1(System.Collections.Generic.IEnumerable{``0}) method assumes that either a sequence or the sequence that meets specified criteria contains only one element. M:System.Linq.Enumerable.SingleOrDefault``1(System.Collections.Generic.IEnumerable{``0}) assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting T:System.InvalidOperationException is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other T:System.Linq.Enumerable method, such as M:System.Linq.Enumerable.FirstOrDefault``1(System.Collections.Generic.IEnumerable{``0}) or M:System.Linq.Enumerable.Where``1(System.Collections.Generic.IEnumerable{``0},System.Func{``0,System.Boolean}).

The F:System.Reflection.Emit.OpCodes.Ldflda Microsoft intermediate language (MSIL) instruction throws an T:System.InvalidOperationException exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. The address of a field can only be accessed from the application domain in which it resides.

You should throw an T:System.InvalidOperationException exception only when the state of your object for some reason does not support a particular method call. That is, the method call is valid in some circumstances or contexts, but is invalid in others.

If the method invocation failure is due to invalid arguments, then T:System.ArgumentException or one of its derived classes, T:System.ArgumentNullException or T:System.ArgumentOutOfRangeException, should be thrown instead.

InvalidOperationException uses the HRESULT COR_E_INVALIDOPERATION, which has the value 0x80131509.

For a list of initial property values for an instance of T:System.InvalidOperationException, see the M:System.InvalidOperationException.#ctor constructors.

Universal Windows Platform
Disponibile da 8
.NET Framework
Disponibile da 1.1
Libreria di classi portabile
Supportato in: piattaforme .NET portabili
Silverlight
Disponibile da 2.0
Windows Phone Silverlight
Disponibile da 7.0
Windows Phone
Disponibile da 8.1

I membri statici pubblici ( Condiviso in Visual Basic) di questo tipo è thread safe. Non tutti i membri di istanza sono garantiti come thread safe.

Torna all'inizio
Mostra: