MissingMemberException Класс

Определение

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

public ref class MissingMemberException : MemberAccessException
public class MissingMemberException : MemberAccessException
[System.Serializable]
public class MissingMemberException : MemberAccessException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class MissingMemberException : MemberAccessException
type MissingMemberException = class
    inherit MemberAccessException
type MissingMemberException = class
    inherit MemberAccessException
    interface ISerializable
[<System.Serializable>]
type MissingMemberException = class
    inherit MemberAccessException
    interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MissingMemberException = class
    inherit MemberAccessException
    interface ISerializable
Public Class MissingMemberException
Inherits MemberAccessException
Наследование
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.

Комментарии

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

MissingMemberException — базовый класс для MissingFieldException и MissingMethodException. Как правило, лучше использовать один из производных классов MissingMemberException , чтобы точно указать характер ошибки. MissingMemberException Создайте исключение, если вы заинтересованы только в захвате общего случая ошибки отсутствующего члена.

MissingMemberException использует COR_E_MISSINGMEMBER HRESULT, имеющий значение 0x80131512.

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

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

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

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

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

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

MissingMemberException(String, Exception)

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

MissingMemberException(String, String)

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

MissingMemberException(String)

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

Поля

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

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

MemberName

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

Signature

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

Свойства

Имя Описание
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 с именем класса, именем члена, подписью отсутствующего члена и дополнительными сведениями об исключении.

GetType()

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

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

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

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

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

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

События

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

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

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

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

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