- Invalid Operation Exception Класс
- Определение
- Комментарии
- Некоторые распространенные причины исключений InvalidOperationException 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
- Приведение Nullable , имеющего значение null, к базовому типу Casting a Nullable that is null to its underlying type
- Вызов метода System. LINQ. Enumerable для пустой коллекции Calling a System.Linq.Enumerable method on an empty collection
- Вызов Enumerable. Single или Enumerable. SingleOrDefault для последовательности без одного элемента Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
- Динамическое обращение к полю домена между приложениями Dynamic cross-application domain field access
- Создание исключения InvalidOperationException Throwing an InvalidOperationException exception
- Прочие сведения Miscellaneous information
- Конструкторы
- Свойства
- Методы
- События
Invalid Operation Exception Класс
Определение
Исключение, которое выдается при вызове метода, недопустимого для текущего состояния объекта. The exception that is thrown when a method call is invalid for the object’s current state.
Комментарии
InvalidOperationException используется в случаях, когда сбой вызова метода вызван по причинам, отличным от недопустимых аргументов. InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Как правило, он вызывается, когда состояние объекта не поддерживает вызов метода. Typically, it is thrown when the state of an object cannot support the method call. Например, InvalidOperationException исключение вызывается такими методами, как: For example, an InvalidOperationException exception is thrown by methods such as:
IEnumerator.MoveNext значение, если объекты коллекции изменяются после создания перечислителя. IEnumerator.MoveNext if objects of a collection are modified after the enumerator is created. Дополнительные сведения см. в разделе изменение коллекции во время итерации. For more information, see Changing a collection while iterating it.
ResourceSet.GetString значение, если набор ресурсов закрывается до вызова метода. ResourceSet.GetString if the resource set is closed before the method call is made.
XContainer.Add, если добавляемый объект или объекты приведут к неправильному структурированному XML-документу. XContainer.Add, if the object or objects to be added would result in an incorrectly structured XML document.
Метод, который пытается управлять пользовательским интерфейсом из потока, который не является основным потоком или потоком пользовательского интерфейса. A method that attempts to manipulate the UI from a thread that is not the main or UI thread.
Поскольку InvalidOperationException исключение может быть создано в самых разных обстоятельствах, важно прочитать сообщение об исключении, возвращаемое Message свойством. Because the InvalidOperationException exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the Message property.
Содержание In this section:
Некоторые распространенные причины исключений InvalidOperationException Some common causes of InvalidOperationException exceptions
В следующих разделах показано, как часто возникают ситуации, в которых InvalidOperationException исключение возникает в приложении. The following sections show how some common cases in which in InvalidOperationException exception is thrown in an app. Способ решения проблемы зависит от конкретной ситуации. How you handle the issue depends on the specific situation. Однако чаще всего исключение возникает из ошибки разработчика, и это InvalidOperationException исключение можно ожидать и избежать. Most commonly, however, the exception results from developer error, and the InvalidOperationException exception can be anticipated and avoided.
Обновление потока пользовательского интерфейса из потока, не относящегося к пользовательскому интерфейсу Updating a UI thread from a non-UI thread
Часто рабочие потоки используются для выполнения некоторой фоновой работы, включающей сбор данных, отображаемых в пользовательском интерфейсе приложения. Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application’s user interface. Тем не менее However. Большинство платформ приложений графического пользовательского интерфейса (графический интерфейс пользователя) для платформа .NET Framework, таких как Windows Forms и Windows Presentation Foundation (WPF), позволяют получать доступ к объектам графического пользовательского интерфейса только из потока, который создает пользовательский интерфейс и управляет им (основным потоком или потоком пользовательского интерфейса). most GUI (graphical user interface) application frameworks for the .NET Framework, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). InvalidOperationExceptionИсключение возникает при попытке доступа к элементу пользовательского интерфейса из потока, отличного от потока пользовательского интерфейса. An InvalidOperationException is thrown when you try to access a UI element from a thread other than the UI thread. Текст сообщения об исключении показан в следующей таблице. The text of the exception message is shown in the following table.
Тип приложения Application Type | Сообщение Message |
---|---|
Приложение WPF WPF app | Вызывающий поток не может получить доступ к этому объекту, так как он принадлежит другому потоку. The calling thread cannot access this object because a different thread owns it. |
Приложение UWP UWP app | Приложение называется интерфейсом, который был маршалирован для другого потока. The application called an interface that was marshaled for a different thread. |
Приложение Windows Forms Windows Forms app | Недопустимая операция между потоками: доступ к элементу управления «TextBox1» осуществляется из потока, отличного от потока, в котором он был создан. Cross-thread operation not valid: Control ‘TextBox1’ accessed from a thread other than the thread it was created on. |
Платформы пользовательского интерфейса для платформа .NET Framework реализуют шаблон Dispatcher , который включает метод для проверки того, выполняется ли вызов элемента пользовательского интерфейса в ПОТОКЕ пользовательского интерфейса, а также другие методы для планирования вызова в ПОТОКЕ пользовательского интерфейса: UI frameworks for the .NET Framework implement a dispatcher pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread:
В приложениях WPF вызовите Dispatcher.CheckAccess метод, чтобы определить, выполняется ли метод в потоке без пользовательского интерфейса. In WPF apps, call the Dispatcher.CheckAccess method to determine if a method is running on a non-UI thread. Он возвращает значение, true Если метод работает в потоке пользовательского интерфейса и false в противном случае. It returns true if the method is running on the UI thread and false otherwise. Вызовите одну из перегрузок Dispatcher.Invoke метода, чтобы запланировать вызов в потоке пользовательского интерфейса. Call one of the overloads of the Dispatcher.Invoke method to schedule the call on the UI thread.
В приложениях UWP проверьте свойство, CoreDispatcher.HasThreadAccess чтобы определить, выполняется ли метод в потоке без пользовательского интерфейса. In UWP apps, check the CoreDispatcher.HasThreadAccess property to determine if a method is running on a non-UI thread. Вызовите CoreDispatcher.RunAsync метод, чтобы выполнить делегат, который обновляет поток пользовательского интерфейса. Call the CoreDispatcher.RunAsync method to execute a delegate that updates the UI thread.
В Windows Forms приложениях используйте свойство, Control.InvokeRequired чтобы определить, выполняется ли метод в потоке без пользовательского интерфейса. In Windows Forms apps, use the Control.InvokeRequired property to determine if a method is running on a non-UI thread. Вызовите одну из перегрузок Control.Invoke метода, чтобы выполнить делегат, который обновляет поток пользовательского интерфейса. Call one of the overloads of the Control.Invoke method to execute a delegate that updates the UI thread.
В следующих примерах показано InvalidOperationException исключение, возникающее при попытке обновить элемент пользовательского интерфейса из потока, отличного от создавшего его потока. The following examples illustrate the InvalidOperationException exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Для каждого примера необходимо создать два элемента управления: Each example requires that you create two controls:
Элемент управления «текстовое поле» с именем textBox1 . A text box control named textBox1 . В Windows Forms приложении следует задать для его свойства значение Multiline true . In a Windows Forms app, you should set its Multiline property to true .
Элемент управления Button с именем threadExampleBtn . A button control named threadExampleBtn . В примере показан обработчик ThreadsExampleBtn_Click для Click события кнопки. The example provides a handler, ThreadsExampleBtn_Click , for the button’s Click event.
В каждом случае threadExampleBtn_Click обработчик событий вызывает DoSomeWork метод дважды. In each case, the threadExampleBtn_Click event handler calls the DoSomeWork method twice. Первый вызов выполняется синхронно и завершился. The first call runs synchronously and succeeds. Но второй вызов, поскольку он выполняется асинхронно в потоке пула потоков, пытается обновить пользовательский интерфейс из потока, не относящегося к пользовательскому интерфейсу. But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. Это приводит к InvalidOperationException исключению. This results in a InvalidOperationException exception.
Приложения WPF и UWP WPF and UWP apps
Следующая версия DoSomeWork метода устраняет исключение в приложении WPF. The following version of the DoSomeWork method eliminates the exception in a WPF app.
Следующая версия DoSomeWork метода устраняет исключение в приложении UWP. The following version of the DoSomeWork method eliminates the exception in a UWP app.
Приложения Windows Forms Windows Forms apps
Следующая версия DoSomeWork метода устраняет исключение в Windows Forms приложении. The following version of the DoSomeWork method eliminates the exception in a Windows Forms app.
Изменение коллекции во время ее итерации Changing a collection while iterating it
foreach Инструкция в C# или For Each оператор в Visual Basic используется для итерации элементов коллекции и чтения или изменения отдельных элементов. The foreach statement in C# or For Each statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. Однако его нельзя использовать для добавления или удаления элементов из коллекции. However, it can’t be used to add or remove items from the collection. При этом создается InvalidOperationException исключение с сообщением, похожее на «коллекция была изменена; Операция перечисления не может быть выполнена «. Doing this throws an InvalidOperationException exception with a message that is similar to, «Collection was modified; enumeration operation may not execute.«
В следующем примере выполняется итерация коллекции целых чисел, которая пытается добавить квадрат каждого целого числа в коллекцию. The following example iterates a collection of integers attempts to add the square of each integer to the collection. В примере создается исключение InvalidOperationException с первым вызовом List .Add метода. The example throws an InvalidOperationException with the first call to the List .Add method.
Исключение можно устранить одним из двух способов, в зависимости от логики приложения: You can eliminate the exception in one of two ways, depending on your application logic:
Если во время итерации в коллекцию необходимо добавить элементы, можно выполнить итерацию по индексу, используя for инструкцию, а не foreach или For Each . 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 . В следующем примере оператор for используется для добавления квадрата чисел из коллекции в коллекцию. The following example uses the for statement to add the square of numbers in the collection to the collection.
Обратите внимание, что перед перебором коллекции необходимо установить число итераций с помощью счетчика внутри цикла, который выполнит цикл соответствующим образом, выполнив итерацию назад, от Count -1 до 0 или, как показано в примере, назначив число элементов в массиве переменной и используя его для установления верхней границы цикла. Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropriately, by iterating backward, from Count — 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. В противном случае, если элемент добавляется в коллекцию при каждой итерации, будет получен бесконечный цикл. Otherwise, if an element is added to the collection on every iteration, an endless loop results.
Если нет необходимости добавлять элементы в коллекцию во время итерации, можно сохранить элементы, добавляемые во временную коллекцию, добавленную при итерации коллекции. If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. В следующем примере этот подход используется для добавления квадрата чисел из коллекции в временную коллекцию, а затем для объединения коллекций в один объект массива. The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object.
Сортировка массива или коллекции, объекты которой невозможно сравнить Sorting an array or collection whose objects cannot be compared
Для методов сортировки общего назначения, таких как Array.Sort(Array) метод или List .Sort() метод, обычно требуется, чтобы хотя бы один из объектов был отсортирован, реализуя IComparable IComparable интерфейс или. General-purpose sorting methods, such as the Array.Sort(Array) method or the List .Sort() method, usually require that at least one of the objects to be sorted implement the IComparable or the IComparable interface. В противном случае коллекция или массив не могут быть отсортированы, а метод создает InvalidOperationException исключение. If not, the collection or array cannot be sorted, and the method throws an InvalidOperationException exception. В следующем примере определяется Person класс, хранится два объекта Person в универсальном List объекте и выполняется попытка их сортировки. The following example defines a Person class, stores two Person objects in a generic List object, and attempts to sort them. Как видно из выходных данных в примере, вызов List .Sort() метода создает исключение InvalidOperationException . As the output from the example shows, the call to the List .Sort() method throws an InvalidOperationException.
Исключение можно устранить одним из трех способов: You can eliminate the exception in any of three ways:
Если тип, который вы пытаетесь отсортировать, можно использовать (то есть если вы управляете его исходным кодом), его можно изменить, чтобы реализовать IComparable интерфейс или IComparable . If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the IComparable or the IComparable interface. Для этого необходимо реализовать IComparable .CompareTo CompareTo метод или. This requires that you implement either the IComparable .CompareTo or the CompareTo method. Добавление реализации интерфейса в существующий тип не является критическим изменением. Adding an interface implementation to an existing type is not a breaking change.
В следующем примере этот подход используется для предоставления IComparable реализации Person класса. The following example uses this approach to provide an IComparable 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.
Если не удается изменить исходный код для типа, который вы пытаетесь отсортировать, можно определить специализированный класс сортировки, реализующий IComparer интерфейс. 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 interface. Можно вызвать перегрузку Sort метода, который включает IComparer параметр. You can call an overload of the Sort method that includes an IComparer parameter. Этот подход особенно удобен, если требуется разработать специализированный класс сортировки, который может сортировать объекты на основе нескольких критериев. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria.
В следующем примере используется подход путем разработки пользовательского PersonComparer класса, который используется для сортировки Person коллекций. The following example uses the approach by developing a custom PersonComparer class that is used to sort Person collections. Затем он передает экземпляр этого класса в List .Sort(IComparer ) метод. It then passes an instance of this class to the List .Sort(IComparer ) method.
Если не удается изменить исходный код для типа, который вы пытаетесь отсортировать, можно создать Comparison делегат для выполнения сортировки. If you cannot modify the source code for the type you are trying to sort, you can create a Comparison delegate to perform the sorting. Сигнатура делегата — The delegate signature is
В следующем примере используется подход путем определения PersonComparison метода, который соответствует Comparison сигнатуре делегата. The following example uses the approach by defining a PersonComparison method that matches the Comparison delegate signature. Затем он передает этот делегат List .Sort(Comparison ) методу. It then passes this delegate to the List .Sort(Comparison ) method.
Приведение Nullable , имеющего значение null, к базовому типу Casting a Nullable that is null to its underlying type
Попытка приведения Nullable значения null к базовому типу вызывает InvalidOperationException исключение и отображает сообщение об ошибке «объект, допускающий значение null, должен иметь значение. Attempting to cast a Nullable value that is null to its underlying type throws an InvalidOperationException exception and displays the error message, «Nullable object must have a value.
В следующем примере создается InvalidOperationException исключение при попытке выполнить итерацию массива, содержащего Nullable(Of Integer) значение. The following example throws an InvalidOperationException exception when it attempts to iterate an array that includes a Nullable(Of Integer) value.
Чтобы предотвратить исключение, сделайте следующее: To prevent the exception:
Используйте Nullable .HasValue свойство, чтобы выбрать только те элементы, которые не являются null . Use the Nullable .HasValue property to select only those elements that are not null .
Вызовите одну из Nullable .GetValueOrDefault перегрузок, чтобы предоставить значение по умолчанию для null значения. Call one of the Nullable .GetValueOrDefault overloads to provide a default value for a null value.
В следующем примере оба варианта позволяют избежать InvalidOperationException исключения. The following example does both to avoid the InvalidOperationException exception.
Вызов метода System. LINQ. Enumerable для пустой коллекции Calling a System.Linq.Enumerable method on an empty collection
Enumerable.AggregateМетоды, Enumerable.Average , Enumerable.First , Enumerable.Last , Enumerable.Max , Enumerable.Min , Enumerable.Single и Enumerable.SingleOrDefault выполняют операции над последовательностью и возвращают один результат. The Enumerable.Aggregate, Enumerable.Average, Enumerable.First, Enumerable.Last, Enumerable.Max, Enumerable.Min, Enumerable.Single, and Enumerable.SingleOrDefault methods perform operations on a sequence and return a single result. Некоторые перегрузки этих методов вызывают InvalidOperationException исключение, если последовательность пуста, а другие перегрузки возвращают null . Some overloads of these methods throw an InvalidOperationException exception when the sequence is empty, while other overloads return null . Enumerable.SingleOrDefaultМетод также вызывает исключение, InvalidOperationException если последовательность содержит более одного элемента. The Enumerable.SingleOrDefault method also throws an InvalidOperationException exception when the sequence contains more than one element.
Большинство методов, которые вызывают исключение, InvalidOperationException являются перегрузками. Most of the methods that throw an InvalidOperationException exception are overloads. Убедитесь, что вы понимаете поведение выбранной перегрузки. Be sure that you understand the behavior of the overload that you choose.
В следующей таблице перечислены сообщения об исключениях из InvalidOperationException объектов исключений, создаваемых вызовами некоторых System.Linq.Enumerable методов. The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to some System.Linq.Enumerable methods.
Метод Method | Сообщение Message |
---|---|
Aggregate Average Last Max Min | Последовательность не содержит элементов Sequence contains no elements |
First | Sequence не содержит соответствующего элемента 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 .
Если ошибка проверки пустой последовательности была непреднамеренной, можно вызвать одну из перегрузок Enumerable.Any перегрузки, чтобы определить, содержит ли последовательность какие-либо элементы. 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.
Вызов Enumerable.Any (IEnumerable , Func ) метода до создания последовательности может повысить производительность, если обрабатываемые данные могут содержать большое количество элементов или операция, создающая последовательность, является дорогостоящей. Calling the Enumerable.Any (IEnumerable , Func ) 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.
Если вы вызвали метод, например, Enumerable.First Enumerable.Last или Enumerable.Single , можно заменить альтернативный метод, например Enumerable.FirstOrDefault , Enumerable.LastOrDefault или Enumerable.SingleOrDefault , который возвращает значение по умолчанию вместо элемента последовательности. 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.
В примерах содержатся дополнительные сведения. The examples provide additional detail.
В следующем примере метод используется Enumerable.Average для вычисления среднего значения последовательности, значение которой больше 4. The following example uses the Enumerable.Average method to compute the average of a sequence whose values are greater than 4. Поскольку значения из исходного массива не превышают 4, в последовательность не включаются значения, а метод создает InvalidOperationException исключение. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an InvalidOperationException exception.
Исключение можно устранить, вызвав метод, Any чтобы определить, содержит ли последовательность какие бы то ни было элементы перед вызовом метода, обрабатывающего последовательность, как показано в следующем примере. The exception can be eliminated by calling the Any method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows.
Enumerable.FirstМетод возвращает первый элемент последовательности или первый элемент последовательности, удовлетворяющий заданному условию. The Enumerable.First method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. Если последовательность пуста и поэтому не имеет первого элемента, то создается InvalidOperationException исключение. If the sequence is empty and therefore does not have a first element, it throws an InvalidOperationException exception.
В следующем примере Enumerable.First (IEnumerable , Func ) метод создает InvalidOperationException исключение, так как массив дбкуериресултс не содержит элемент больше 4. In the following example, the Enumerable.First (IEnumerable , Func ) method throws an InvalidOperationException exception because the dbQueryResults array doesn’t contain an element greater than 4.
Вы можете вызвать Enumerable.FirstOrDefault метод вместо того, Enumerable.First чтобы возвращать указанное или значение по умолчанию. You can call the Enumerable.FirstOrDefault method instead of Enumerable.First to return a specified or default value. Если метод не находит первый элемент в последовательности, он возвращает значение по умолчанию для этого типа данных. If the method does not find a first element in the sequence, it returns the default value for that data type. Значение по умолчанию — null для ссылочного типа, ноль для типа данных numeric и DateTime.MinValue для DateTime типа. The default value is null for a reference type, zero for a numeric data type, and DateTime.MinValue for the DateTime type.
Анализ значения, возвращаемого методом, Enumerable.FirstOrDefault часто осложняется тем, что значение по умолчанию типа может быть допустимым значением в последовательности. Interpreting the value returned by the Enumerable.FirstOrDefault method is often complicated by the fact that the default value of the type can be a valid value in the sequence. В этом случае вы вызываете метод, Enumerable.Any чтобы определить, содержит ли последовательность допустимые члены перед вызовом Enumerable.First метода. In this case, you an call the Enumerable.Any method to determine whether the sequence has valid members before calling the Enumerable.First method.
В следующем примере вызывается Enumerable.FirstOrDefault (IEnumerable , Func ) метод для предотвращения InvalidOperationException исключения, вызываемого в предыдущем примере. The following example calls the Enumerable.FirstOrDefault (IEnumerable , Func ) method to prevent the InvalidOperationException exception thrown in the previous example.
Вызов Enumerable. Single или Enumerable. SingleOrDefault для последовательности без одного элемента Calling Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element
Enumerable.SingleМетод возвращает единственный элемент последовательности или единственный элемент последовательности, соответствующий заданному условию. The Enumerable.Single method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. Если в последовательности нет элементов или имеется более одного элемента, метод создает InvalidOperationException исключение. If there are no elements in the sequence, or if there is more than one element , the method throws an InvalidOperationException exception.
Метод можно использовать Enumerable.SingleOrDefault для возврата значения по умолчанию вместо создания исключения, если последовательность не содержит элементов. You can use the Enumerable.SingleOrDefault method to return a default value instead of throwing an exception when the sequence contains no elements. Однако Enumerable.SingleOrDefault метод все равно вызывает исключение, InvalidOperationException если последовательность содержит более одного элемента. However, the Enumerable.SingleOrDefault method still throws an InvalidOperationException exception when the sequence contains more than one element.
В следующей таблице перечислены сообщения об исключениях из InvalidOperationException объектов исключений, создаваемых вызовами Enumerable.Single Enumerable.SingleOrDefault методов и. The following table lists the exception messages from the InvalidOperationException exception objects thrown by calls to the Enumerable.Single and Enumerable.SingleOrDefault methods.
Метод Method | Сообщение Message |
---|---|
Single | Sequence не содержит соответствующего элемента Sequence contains no matching element |
Single SingleOrDefault | Последовательность содержит более одного соответствующего элемента Sequence contains more than one matching element |
В следующем примере вызов Enumerable.Single метода вызывает InvalidOperationException исключение, так как последовательность не содержит элемент больше 4. In the following example, the call to the Enumerable.Single method throws an InvalidOperationException exception because the sequence doesn’t have an element greater than 4.
В следующем примере предпринимается попытка предотвратить InvalidOperationException исключение, возникающее, если последовательность пуста, вместо этого вызывается Enumerable.SingleOrDefault метод. The following example attempts to prevent the InvalidOperationException exception thrown when a sequence is empty by instead calling the Enumerable.SingleOrDefault method. Однако, поскольку эта последовательность возвращает несколько элементов, значение которых больше 2, оно также вызывает InvalidOperationException исключение. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an InvalidOperationException exception.
При вызове Enumerable.Single метода предполагается, что либо последовательность, либо последовательность, отвечающая указанным критериям, содержат только один элемент. Calling the Enumerable.Single method assumes that either a sequence or the sequence that meets specified criteria contains only one element. Enumerable.SingleOrDefault Предполагается, что последовательность имеет ноль или один результат, но больше нет. Enumerable.SingleOrDefault assumes a sequence with zero or one result, but no more. Если это предположение является предопределенной на вашей части и эти условия не выполняются, то подходящее исключение или перехват полученного результата InvalidOperationException . If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting InvalidOperationException is appropriate. В противном случае или, если предполагается, что при некоторой частоте возникнут недопустимые условия, следует рассмотреть возможность использования другого Enumerable метода, например FirstOrDefault или 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.
Динамическое обращение к полю домена между приложениями Dynamic cross-application domain field access
OpCodes.LdfldaИнструкция MSIL выдает InvalidOperationException исключение, если объект, содержащий поле, адрес которого вы пытаетесь извлечь, не находится в домене приложения, в котором выполняется код. The OpCodes.Ldflda Microsoft intermediate language (MSIL) instruction throws an InvalidOperationException exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. Доступ к адресу поля возможен только из домена приложения, в котором оно находится. The address of a field can only be accessed from the application domain in which it resides.
Создание исключения InvalidOperationException Throwing an InvalidOperationException exception
Исключение следует вызывать InvalidOperationException только в том случае, если состояние объекта по какой-либо причине не поддерживает определенный вызов метода. You should throw an InvalidOperationException exception only when the state of your object for some reason does not support a particular method call. Это значит, что вызов метода допустим в некоторых обстоятельствах или контекстах, но является недопустимым в других. That is, the method call is valid in some circumstances or contexts, but is invalid in others.
Если ошибка вызова метода вызвана недопустимыми аргументами, то ArgumentException ArgumentNullException ArgumentOutOfRangeException вместо этого следует вызывать исключение или один из его производных классов. If the method invocation failure is due to invalid arguments, then ArgumentException or one of its derived classes, ArgumentNullException or ArgumentOutOfRangeException, should be thrown instead.
Прочие сведения Miscellaneous information
InvalidOperationException использует COR_E_INVALIDOPERATION HRESULT, имеющий значение 0x80131509. InvalidOperationException uses the HRESULT COR_E_INVALIDOPERATION, which has the value 0x80131509.
Список начальных значений свойств для экземпляра InvalidOperationException, см. в разделе InvalidOperationException конструкторы. For a list of initial property values for an instance of InvalidOperationException, see the InvalidOperationException constructors.
Конструкторы
Инициализирует новый экземпляр класса InvalidOperationException. Initializes a new instance of the InvalidOperationException class.
Инициализирует новый экземпляр класса InvalidOperationException с сериализованными данными. Initializes a new instance of the InvalidOperationException class with serialized data.
Инициализирует новый экземпляр класса InvalidOperationException с указанным сообщением об ошибке. Initializes a new instance of the InvalidOperationException class with a specified error message.
Инициализирует новый экземпляр класса InvalidOperationException указанным сообщением об ошибке и ссылкой на внутреннее исключение, вызвавшее данное исключение. Initializes a new instance of the InvalidOperationException class with a specified error message and a reference to the inner exception that is the cause of this exception.
Свойства
Возвращает коллекцию пар «ключ-значение», предоставляющую дополнительные сведения об исключении. Gets a collection of key/value pairs that provide additional user-defined information about the exception.
(Унаследовано от Exception)
Получает или задает ссылку на файл справки, связанный с этим исключением. Gets or sets a link to the help file associated with this exception.
(Унаследовано от Exception)
Возвращает или задает HRESULT — кодированное числовое значение, присвоенное определенному исключению. Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.
(Унаследовано от Exception)
Возвращает экземпляр класса Exception, который вызвал текущее исключение. Gets the Exception instance that caused the current exception.
(Унаследовано от Exception)
Возвращает сообщение, описывающее текущее исключение. Gets a message that describes the current exception.
(Унаследовано от Exception)
Возвращает или задает имя приложения или объекта, вызывавшего ошибку. Gets or sets the name of the application or the object that causes the error.
(Унаследовано от Exception)
Получает строковое представление непосредственных кадров в стеке вызова. Gets a string representation of the immediate frames on the call stack.
(Унаследовано от Exception)
Возвращает метод, создавший текущее исключение. Gets the method that throws the current exception.
(Унаследовано от Exception)
Методы
Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.
(Унаследовано от Object)
При переопределении в производном классе возвращает исключение Exception, которое является первопричиной одного или нескольких последующих исключений. When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.
(Унаследовано от Exception)
Служит хэш-функцией по умолчанию. Serves as the default hash function.
(Унаследовано от Object)
При переопределении в производном классе задает объект SerializationInfo со сведениями об исключении. When overridden in a derived class, sets the SerializationInfo with information about the exception.
(Унаследовано от Exception)
Возвращает тип среды выполнения текущего экземпляра. Gets the runtime type of the current instance.
(Унаследовано от Exception)
Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.
(Унаследовано от Object)
Создает и возвращает строковое представление текущего исключения. Creates and returns a string representation of the current exception.
(Унаследовано от Exception)
События
Возникает, когда исключение сериализовано для создания объекта состояния исключения, содержащего сериализованные данные об исключении. Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.