MissingFieldException Класс

Определение

Исключение, которое возникает при попытке динамически получить доступ к полю, которое не существует. Если поле в библиотеке классов было удалено или переименовано, перекомпилируйте все сборки, ссылающиеся на нее.

public ref class MissingFieldException : MissingMemberException
public class MissingFieldException : MissingMemberException
[System.Serializable]
public class MissingFieldException : MissingMemberException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class MissingFieldException : MissingMemberException
type MissingFieldException = class
    inherit MissingMemberException
type MissingFieldException = class
    inherit MissingMemberException
    interface ISerializable
[<System.Serializable>]
type MissingFieldException = class
    inherit MissingMemberException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MissingFieldException = class
    inherit MissingMemberException
    interface ISerializable
Public Class MissingFieldException
Inherits MissingMemberException
Наследование
Наследование
Атрибуты
Реализации

Примеры

В этом примере показано, что происходит, если вы пытаетесь использовать отражение для вызова метода, который не существует, и доступа к полю, которое не существует. Приложение восстанавливается путем перехвата MissingMethodException, MissingFieldExceptionи MissingMemberException.

using System;
using System.Reflection;

public class App
{
    public static void Main()
    {

        try
        {
            // Attempt to call a static DoSomething method defined in the App class.
            // However, because the App class does not define this method,
            // a MissingMethodException is thrown.
            typeof(App).InvokeMember("DoSomething", BindingFlags.Static |
                BindingFlags.InvokeMethod, null, null, null);
        }
        catch (MissingMethodException e)
        {
            // Show the user that the DoSomething method cannot be called.
            Console.WriteLine("Unable to call the DoSomething method: {0}", e.Message);
        }

        try
        {
            // Attempt to access a static AField field defined in the App class.
            // However, because the App class does not define this field,
            // a MissingFieldException is thrown.
            typeof(App).InvokeMember("AField", BindingFlags.Static | BindingFlags.SetField,
                null, null, new Object[] { 5 });
        }
        catch (MissingFieldException e)
        {
         // Show the user that the AField field cannot be accessed.
         Console.WriteLine("Unable to access the AField field: {0}", e.Message);
        }

        try
        {
            // Attempt to access a static AnotherField field defined in the App class.
            // However, because the App class does not define this field,
            // a MissingFieldException is thrown.
            typeof(App).InvokeMember("AnotherField", BindingFlags.Static |
                BindingFlags.GetField, null, null, null);
        }
        catch (MissingMemberException e)
        {
         // Notice that this code is catching MissingMemberException which is the
         // base class of MissingMethodException and MissingFieldException.
         // Show the user that the AnotherField field cannot be accessed.
         Console.WriteLine("Unable to access the AnotherField field: {0}", e.Message);
        }
    }
}
// This code example produces the following output:
//
// Unable to call the DoSomething method: Method 'App.DoSomething' not found.
// Unable to access the AField field: Field 'App.AField' not found.
// Unable to access the AnotherField field: Field 'App.AnotherField' not found.
open System
open System.Reflection

type App = class end

try
    // Attempt to call a static DoSomething method defined in the App class.
    // However, because the App class does not define this method,
    // a MissingMethodException is thrown.
    typeof<App>.InvokeMember("DoSomething", BindingFlags.Static ||| BindingFlags.InvokeMethod, null, null, null)
    |> ignore
with :? MissingMethodException as e ->
    // Show the user that the DoSomething method cannot be called.
    printfn $"Unable to call the DoSomething method: {e.Message}"

try
    // Attempt to access a static AField field defined in the App class.
    // However, because the App class does not define this field,
    // a MissingFieldException is thrown.
    typeof<App>.InvokeMember("AField", BindingFlags.Static ||| BindingFlags.SetField, null, null, [| box 5 |])
    |> ignore
with :? MissingFieldException as e ->
    // Show the user that the AField field cannot be accessed.
    printfn $"Unable to access the AField field: {e.Message}"

try
    // Attempt to access a static AnotherField field defined in the App class.
    // However, because the App class does not define this field,
    // a MissingFieldException is thrown.
    typeof<App>.InvokeMember("AnotherField", BindingFlags.Static ||| BindingFlags.GetField, null, null, null)
    |> ignore
with :? MissingMemberException as e ->
    // Notice that this code is catching MissingMemberException which is the
    // base class of MissingMethodException and MissingFieldException.
    // Show the user that the AnotherField field cannot be accessed.
    printfn $"Unable to access the AnotherField field: {e.Message}"
// This code example produces the following output:
//     Unable to call the DoSomething method: Method 'App.DoSomething' not found.
//     Unable to access the AField field: Field 'App.AField' not found.
//     Unable to access the AnotherField field: Field 'App.AnotherField' not found.
Imports System.Reflection

Public Class App
    Public Shared Sub Main() 
        Try
            ' Attempt to call a static DoSomething method defined in the App class.
            ' However, because the App class does not define this method, 
            ' a MissingMethodException is thrown.
            GetType(App).InvokeMember("DoSomething", BindingFlags.Static Or BindingFlags.InvokeMethod, _
                                       Nothing, Nothing, Nothing)
        Catch e As MissingMethodException
            ' Show the user that the DoSomething method cannot be called.
            Console.WriteLine("Unable to call the DoSomething method: {0}", e.Message)
        End Try
        Try
            ' Attempt to access a static AField field defined in the App class.
            ' However, because the App class does not define this field, 
            ' a MissingFieldException is thrown.
            GetType(App).InvokeMember("AField", BindingFlags.Static Or BindingFlags.SetField, _
                                       Nothing, Nothing, New [Object]() {5})
        Catch e As MissingFieldException
            ' Show the user that the AField field cannot be accessed.
            Console.WriteLine("Unable to access the AField field: {0}", e.Message)
        End Try
        Try
            ' Attempt to access a static AnotherField field defined in the App class.
            ' However, because the App class does not define this field, 
            ' a MissingFieldException is thrown.
            GetType(App).InvokeMember("AnotherField", BindingFlags.Static Or BindingFlags.GetField, _
                                       Nothing, Nothing, Nothing)
        Catch e As MissingMemberException
            ' Notice that this code is catching MissingMemberException which is the  
            ' base class of MissingMethodException and MissingFieldException.
            ' Show the user that the AnotherField field cannot be accessed.
            Console.WriteLine("Unable to access the AnotherField field: {0}", e.Message)
        End Try
    End Sub 
End Class 
' This code example produces the following output:
'
' Unable to call the DoSomething method: Method 'App.DoSomething' not found.
' Unable to access the AField field: Field 'App.AField' not found.
' Unable to access the AnotherField field: Field 'App.AnotherField' not found.

Комментарии

Обычно ошибка компиляции создается, если код пытается получить доступ к несуществующему члену класса. MissingFieldException предназначен для обработки случаев, когда попытка динамически получить доступ к переименованию или удалению поля сборки, на которую не ссылается строгое имя. Вызывается MissingFieldException при попытке кода в зависимой сборке получить доступ к отсутствующим полю в сборке, которая была изменена.

MissingFieldException использует COR_E_MISSINGFIELD HRESULT, имеющий значение 0x80131511.

Список начальных значений свойств для экземпляра MissingFieldExceptionсм. в конструкторах MissingFieldException.

Конструкторы

Имя Описание
MissingFieldException()

Инициализирует новый экземпляр класса MissingFieldException.

MissingFieldException(SerializationInfo, StreamingContext)
Устаревшие..

Инициализирует новый экземпляр MissingFieldException класса сериализованными данными.

MissingFieldException(String, Exception)

Инициализирует новый экземпляр MissingFieldException класса с указанным сообщением об ошибке и ссылкой на внутреннее исключение, которое является причиной этого исключения.

MissingFieldException(String, String)

Инициализирует новый экземпляр MissingFieldException класса с указанным именем класса и именем поля.

MissingFieldException(String)

Инициализирует новый экземпляр MissingFieldException класса с указанным сообщением об ошибке.

Поля

Имя Описание
ClassName

Содержит имя класса отсутствующего элемента.

(Унаследовано от MissingMemberException)
MemberName

Содержит имя отсутствующего элемента.

(Унаследовано от MissingMemberException)
Signature

Содержит подпись отсутствующего элемента.

(Унаследовано от MissingMemberException)

Свойства

Имя Описание
Data

Возвращает коллекцию пар "ключ-значение", которые предоставляют дополнительные пользовательские сведения об исключении.

(Унаследовано от Exception)
HelpLink

Возвращает или задает ссылку на файл справки, связанный с этим исключением.

(Унаследовано от Exception)
HResult

Возвращает или задает HRESULT, закодированное числовое значение, назначенное определенному исключению.

(Унаследовано от Exception)
InnerException

Exception Возвращает экземпляр, вызвавшего текущее исключение.

(Унаследовано от Exception)
Message

Возвращает текстовую строку с подписью отсутствующих полей, имени класса и имени поля. Это свойство доступно только для чтения.

Source

Возвращает или задает имя приложения или объекта, вызывающего ошибку.

(Унаследовано от Exception)
StackTrace

Возвращает строковое представление непосредственных кадров в стеке вызовов.

(Унаследовано от Exception)
TargetSite

Возвращает метод, который вызывает текущее исключение.

(Унаследовано от Exception)

Методы

Имя Описание
Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetBaseException()

При переопределении в производном классе возвращает Exception первопричину одного или нескольких последующих исключений.

(Унаследовано от Exception)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetObjectData(SerializationInfo, StreamingContext)
Устаревшие..

Задает объект SerializationInfo с именем класса, именем члена, подписью отсутствующего члена и дополнительными сведениями об исключении.

(Унаследовано от MissingMemberException)
GetType()

Возвращает тип среды выполнения текущего экземпляра.

(Унаследовано от Exception)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
ToString()

Создает и возвращает строковое представление текущего исключения.

(Унаследовано от Exception)

События

Имя Описание
SerializeObjectState
Устаревшие..

Происходит при сериализации исключения для создания объекта состояния исключения, содержащего сериализованные данные об исключении.

(Унаследовано от Exception)

Применяется к

См. также раздел