DynamicMethod Класс

Определение

Определяет и представляет динамический метод, который можно скомпилировать, выполнить и отменить. Удаленные методы доступны для сборки мусора.

public ref class DynamicMethod sealed : System::Reflection::MethodInfo
public sealed class DynamicMethod : System.Reflection.MethodInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : System.Reflection.MethodInfo
type DynamicMethod = class
    inherit MethodInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
type DynamicMethod = class
    inherit MethodInfo
Public NotInheritable Class DynamicMethod
Inherits MethodInfo
Наследование
Атрибуты

Примеры

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

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;

public class Test
{
    // Declare a delegate type that can be used to execute the completed
    // dynamic method.
    private delegate int HelloDelegate(string msg, int ret);

    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This dynamic method has a String
        // parameter and an Integer parameter.
        Type[] helloArgs = {typeof(string), typeof(int)};

        // Create a dynamic method with the name "Hello", a return type
        // of Integer, and two parameters whose types are specified by
        // the array helloArgs. Create the method in the module that
        // defines the String class.
        DynamicMethod hello = new DynamicMethod("Hello",
            typeof(int),
            helloArgs,
            typeof(string).Module);

        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = {typeof(string)};
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString = typeof(Console).GetMethod("WriteLine",
            writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method,
        // using a stream size larger than the IL that will be
        // emitted.
        ILGenerator il = hello.GetILGenerator(256);
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);

        // Add parameter information to the dynamic method. (This is not
        // necessary, but can be useful for debugging.) For each parameter,
        // identified by position, supply the parameter attributes and a
        // parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message");
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn");

        // Create a delegate that represents the dynamic method. This
        // action completes the method. Any further attempts to
        // change the method are ignored.
        HelloDelegate hi =
            (HelloDelegate) hello.CreateDelegate(typeof(HelloDelegate));

        // Use the delegate to execute the dynamic method.
        Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

        // Execute it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned: " + retval);

        Console.WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = {"\r\nHello, World!", 42};
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and value-type arguments
        // must be boxed.
        object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));
        Console.WriteLine("hello.Invoke returned: " + objRet);

        Console.WriteLine("\r\n ----- Display information about the dynamic method -----");
        // Display MethodAttributes for the dynamic method, set when
        // the dynamic method was created.
        Console.WriteLine("\r\nMethod Attributes: {0}", hello.Attributes);

        // Display the calling convention of the dynamic method, set when the
        // dynamic method was created.
        Console.WriteLine("\r\nCalling convention: {0}", hello.CallingConvention);

        // Display the declaring type, which is always null for dynamic
        // methods.
        if (hello.DeclaringType == null)
        {
            Console.WriteLine("\r\nDeclaringType is always null for dynamic methods.");
        }
        else
        {
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType);
        }

        // Display the default value for InitLocals.
        if (hello.InitLocals)
        {
            Console.Write("\r\nThis method contains verifiable code.");
        }
        else
        {
            Console.Write("\r\nThis method contains unverifiable code.");
        }
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals);

        // Display the module specified when the dynamic method was created.
        Console.WriteLine("\r\nModule: {0}", hello.Module);

        // Display the name specified when the dynamic method was created.
        // Note that the name can be blank.
        Console.WriteLine("\r\nName: {0}", hello.Name);

        // For dynamic methods, the reflected type is always null.
        if (hello.ReflectedType == null)
        {
            Console.WriteLine("\r\nReflectedType is null.");
        }
        else
        {
            Console.WriteLine("\r\nReflectedType: {0}", hello.ReflectedType);
        }

        if (hello.ReturnParameter == null)
        {
            Console.WriteLine("\r\nMethod has no return parameter.");
        }
        else
        {
            Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
        }

        // If the method has no return type, ReturnType is System.Void.
        Console.WriteLine("\r\nReturn type: {0}", hello.ReturnType);

        // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        // that can be used to enumerate the custom attributes of the
        // return value. At present, there is no way to set such custom
        // attributes, so the list is empty.
        if (hello.ReturnType == typeof(void))
        {
            Console.WriteLine("The method has no return type.");
        }
        else
        {
            ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
            object[] returnAttributes = caProvider.GetCustomAttributes(true);
            if (returnAttributes.Length == 0)
            {
                Console.WriteLine("\r\nThe return type has no custom attributes.");
            }
            else
            {
                Console.WriteLine("\r\nThe return type has the following custom attributes:");
                foreach( object attr in returnAttributes )
                {
                    Console.WriteLine("\t{0}", attr.ToString());
                }
            }
        }

        Console.WriteLine("\r\nToString: {0}", hello.ToString());

        // Display parameter information.
        ParameterInfo[] parameters = hello.GetParameters();
        Console.WriteLine("\r\nParameters: name, type, ParameterAttributes");
        foreach( ParameterInfo p in parameters )
        {
            Console.WriteLine("\t{0}, {1}, {2}",
                p.Name, p.ParameterType, p.Attributes);
        }
    }
}

/* This code example produces the following output:

Use the delegate to execute the dynamic method:

Hello, World!
Invoking delegate hi("Hello, World!", 42) returned: 42

Hi, Mom!
Invoking delegate hi("Hi, Mom!", 5280) returned: 5280

Use the Invoke method to execute the dynamic method:

Hello, World!
hello.Invoke returned: 42

 ----- Display information about the dynamic method -----

Method Attributes: PrivateScope, Public, Static

Calling convention: Standard

DeclaringType is always null for dynamic methods.

This method contains verifiable code. (InitLocals = True)

Module: CommonLanguageRuntimeLibrary

Name: Hello

ReflectedType is null.

Method has no return parameter.

Return type: System.Int32

The return type has no custom attributes.

ToString: Int32 Hello(System.String, Int32)

Parameters: name, type, ParameterAttributes
        message, System.String, In
        valueToReturn, System.Int32, In
 */
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Globalization

Public Class Test
    ' Declare a delegate type that can be used to execute the completed
    ' dynamic method. 
    Private Delegate Function HelloDelegate(ByVal msg As String, _
        ByVal ret As Integer) As Integer

    Public Shared Sub Main()
        ' Create an array that specifies the types of the parameters
        ' of the dynamic method. This dynamic method has a String
        ' parameter and an Integer parameter.
        Dim helloArgs() As Type = {GetType(String), GetType(Integer)}

        ' Create a dynamic method with the name "Hello", a return type
        ' of Integer, and two parameters whose types are specified by
        ' the array helloArgs. Create the method in the module that
        ' defines the String class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(String).Module)

        ' Create an array that specifies the parameter types of the
        ' overload of Console.WriteLine to be used in Hello.
        Dim writeStringArgs() As Type = {GetType(String)}
        ' Get the overload of Console.WriteLine that has one
        ' String parameter.
        Dim writeString As MethodInfo = GetType(Console). _
            GetMethod("WriteLine", writeStringArgs) 

        ' Get an ILGenerator and emit a body for the dynamic method,
        ' using a stream size larger than the IL that will be
        ' emitted.
        Dim il As ILGenerator = hello.GetILGenerator(256)
        ' Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0)
        ' Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, Nothing)
        ' The Hello method returns the value of the second argument;
        ' to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1)
        il.Emit(OpCodes.Ret)

        ' Add parameter information to the dynamic method. (This is not
        ' necessary, but can be useful for debugging.) For each parameter,
        ' identified by position, supply the parameter attributes and a 
        ' parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message")
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn")

        ' Create a delegate that represents the dynamic method. This
        ' action completes the method. Any further attempts to
        ' change the method are ignored.
    Dim hi As HelloDelegate = _
            CType(hello.CreateDelegate(GetType(HelloDelegate)), HelloDelegate)

        ' Use the delegate to execute the dynamic method.
        Console.WriteLine(vbCrLf & "Use the delegate to execute the dynamic method:")
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Invoking delegate hi(""Hello, World!"", 42) returned: " _
            & retval & ".")

        ' Execute it again, with different arguments.
        retval = hi(vbCrLf & "Hi, Mom!", 5280)
        Console.WriteLine("Invoking delegate hi(""Hi, Mom!"", 5280) returned: " _
            & retval & ".")

        Console.WriteLine(vbCrLf & "Use the Invoke method to execute the dynamic method:")
        ' Create an array of arguments to use with the Invoke method.
        Dim invokeArgs() As Object = {vbCrLf & "Hello, World!", 42}
        ' Invoke the dynamic method using the arguments. This is much
        ' slower than using the delegate, because you must create an
        ' array to contain the arguments, and value-type arguments
        ' must be boxed.
        Dim objRet As Object = hello.Invoke(Nothing, _
            BindingFlags.ExactBinding, Nothing, invokeArgs, _
            New CultureInfo("en-us"))
        Console.WriteLine("hello.Invoke returned: {0}", objRet)

        Console.WriteLine(vbCrLf & _
            " ----- Display information about the dynamic method -----")
        ' Display MethodAttributes for the dynamic method, set when 
        ' the dynamic method was created.
        Console.WriteLine(vbCrLf & "Method Attributes: {0}", _
            hello.Attributes)

        ' Display the calling convention of the dynamic method, set when the 
        ' dynamic method was created.
        Console.WriteLine(vbCrLf & "Calling convention: {0}", _ 
            hello.CallingConvention)

        ' Display the declaring type, which is always Nothing for dynamic
        ' methods.
        If hello.DeclaringType Is Nothing Then
            Console.WriteLine(vbCrLf & "DeclaringType is always Nothing for dynamic methods.")
        Else
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType)
        End If

        ' Display the default value for InitLocals.
        If hello.InitLocals Then
            Console.Write(vbCrLf & "This method contains verifiable code.")
        Else
            Console.Write(vbCrLf & "This method contains unverifiable code.")
        End If
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals)

        ' Display the module specified when the dynamic method was created.
        Console.WriteLine(vbCrLf & "Module: {0}", hello.Module)

        ' Display the name specified when the dynamic method was created.
        ' Note that the name can be blank.
        Console.WriteLine(vbCrLf & "Name: {0}", hello.Name)

        ' For dynamic methods, the reflected type is always Nothing.
        If hello.ReflectedType Is Nothing Then
            Console.WriteLine(vbCrLf & "ReflectedType is Nothing.")
        Else
            Console.WriteLine(vbCrLf & "ReflectedType: {0}", _
                hello.ReflectedType)
        End If

        If hello.ReturnParameter Is Nothing Then
            Console.WriteLine(vbCrLf & "Method has no return parameter.")
        Else
            Console.WriteLine(vbCrLf & "Return parameter: {0}", _
                hello.ReturnParameter)
        End If

        ' If the method has no return type, ReturnType is System.Void.
        Console.WriteLine(vbCrLf & "Return type: {0}", hello.ReturnType)           

        ' ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        ' that can be used to enumerate the custom attributes of the
        ' return value. At present, there is no way to set such custom
        ' attributes, so the list is empty.
        If hello.ReturnType Is GetType(System.Void) Then
            Console.WriteLine("The method has no return type.")
        Else
            Dim caProvider As ICustomAttributeProvider = _
                hello.ReturnTypeCustomAttributes
            Dim returnAttributes() As Object = _
                caProvider.GetCustomAttributes(True)
            If returnAttributes.Length = 0 Then
                Console.WriteLine(vbCrLf _
                    & "The return type has no custom attributes.")
            Else
                Console.WriteLine(vbCrLf _
                    & "The return type has the following custom attributes:")
                For Each attr As Object In returnAttributes
                    Console.WriteLine(vbTab & attr.ToString())
                Next attr
            End If
        End If

        Console.WriteLine(vbCrLf & "ToString: " & hello.ToString())

        ' Display parameter information.
        Dim parameters() As ParameterInfo = hello.GetParameters()
        Console.WriteLine(vbCrLf & "Parameters: name, type, ParameterAttributes")
        For Each p As ParameterInfo In parameters
            Console.WriteLine(vbTab & "{0}, {1}, {2}", _ 
                p.Name, p.ParameterType, p.Attributes)
        Next p
    End Sub
End Class

' This code example produces the following output:
'
'Use the delegate to execute the dynamic method:
'
'Hello, World!
'Invoking delegate hi("Hello, World!", 42) returned: 42.
'
'Hi, Mom!
'Invoking delegate hi("Hi, Mom!", 5280) returned: 5280.
'
'Use the Invoke method to execute the dynamic method:
'
'Hello, World!
'hello.Invoke returned: 42
'
' ----- Display information about the dynamic method -----
'
'Method Attributes: PrivateScope, Public, Static
'
'Calling convention: Standard
'
'DeclaringType is always Nothing for dynamic methods.
'
'This method contains verifiable code. (InitLocals = True)
'
'Module: CommonLanguageRuntimeLibrary
'
'Name: Hello
'
'ReflectedType is Nothing.
'
'Method has no return parameter.
'
'Return type: System.Int32
'
'The return type has no custom attributes.
'
'ToString: Int32 Hello(System.String, Int32)
'
'Parameters: name, type, ParameterAttributes
'        message, System.String, In
'        valueToReturn, System.Int32, In

Комментарии

Дополнительные сведения об этом API см. в дополнительных примечаниях API для DynamicMethod.

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

Имя Описание
DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)

Создает динамический метод, который является глобальным для модуля, указывая имя метода, атрибуты, соглашение о вызове, тип возвращаемого значения, типы параметров, модуль и следует ли проверять видимость JIT для типов и членов, к которым обращается Microsoft промежуточный язык (MSIL) динамического метода.

DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)

Создает динамический метод, указывая имя метода, атрибуты, соглашение о вызове, тип возвращаемого типа, типы параметров, тип, с которым логически связан динамический метод, и следует ли пропускать проверки видимости JIT для типов и членов, к которым обращается Microsoft промежуточный язык (MSIL) динамического метода.

DynamicMethod(String, Type, Type[], Boolean)

Инициализирует анонимный динамический метод, указывая имя метода, тип возвращаемого значения, типы параметров, а также следует ли пропускать проверки видимости JIT для типов и членов, к которым обращается Microsoft промежуточный язык (MSIL) динамического метода.

DynamicMethod(String, Type, Type[], Module, Boolean)

Создает динамический метод, который является глобальным для модуля, указывая имя метода, тип возвращаемого значения, типы параметров, модуль и следует ли пропускать проверки видимости JIT для типов и членов, к которым обращается Microsoft промежуточный язык (MSIL) динамического метода.

DynamicMethod(String, Type, Type[], Module)

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

DynamicMethod(String, Type, Type[], Type, Boolean)

Создает динамический метод, указывая имя метода, возвращаемый тип, типы параметров, тип, с которым динамический метод логически связан, и следует ли проверять видимость JIT для типов и членов, к которым обращается Microsoft промежуточный язык (MSIL) динамического метода.

DynamicMethod(String, Type, Type[], Type)

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

DynamicMethod(String, Type, Type[])

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

Свойства

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

Возвращает атрибуты, указанные при создании динамического метода.

CallingConvention

Получает соглашение о вызовах, указанное при создании динамического метода.

ContainsGenericParameters

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

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

Возвращает коллекцию, содержащую настраиваемые атрибуты этого члена.

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

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

InitLocals

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

IsAbstract

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

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

Получает значение, указывающее, описывается ли потенциальная видимость этого метода или конструктора Assembly; то есть метод или конструктор не отображается в большинстве других типов в той же сборке и не отображается производным типам за пределами сборки.

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

Возвращает значение, указывающее, ссылается ли этот MemberInfo объект на одну или несколько сборок, содержащихся в коллекционируемых AssemblyLoadContextобъектах.

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

Определяет и представляет динамический метод, который можно скомпилировать, выполнить и отменить. Удаленные методы доступны для сборки мусора.

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

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

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

Возвращает значение, указывающее, описывается Familyли видимость этого метода или конструктора; то есть метод или конструктор видим только в его классе и производных классах.

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

Возвращает значение, указывающее, описывается FamANDAssemли видимость этого метода или конструктора; то есть метод или конструктор можно вызывать производными классами, но только в том случае, если они находятся в одной сборке.

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

Получает значение, указывающее, описывается FamORAssemли потенциальная видимость этого метода или конструктора; то есть метод или конструктор можно вызывать производными классами, где бы они ни находились, и классами в одной сборке.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

IsSecurityCritical

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

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

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

IsSecuritySafeCritical

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

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

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

IsSecurityTransparent

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

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

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

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

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

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

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

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

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

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

Возвращает значение, определяющее элемент метаданных.

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

Не поддерживается для динамических методов.

MethodImplementationFlags

Определяет и представляет динамический метод, который можно скомпилировать, выполнить и отменить. Удаленные методы доступны для сборки мусора.

MethodImplementationFlags

Возвращает флаги, указывающие MethodImplAttributes атрибуты реализации метода.

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

Получает модуль, с которым динамический метод логически связан.

Module

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

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

Возвращает имя динамического метода.

ReflectedType

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

ReturnParameter

Возвращает возвращаемый параметр динамического метода.

ReturnType

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

ReturnTypeCustomAttributes

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

ReturnTypeCustomAttributes

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

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

Методы

Имя Описание
CreateDelegate(Type, Object)

Завершает динамический метод и создает делегат, который можно использовать для его выполнения, указав тип делегата и объект, к которому привязан делегат.

CreateDelegate(Type)

Завершает динамический метод и создает делегат, который можно использовать для его выполнения.

CreateDelegate<T>()

Создает делегат типа T из этого метода.

(Унаследовано от MethodInfo)
CreateDelegate<T>(Object)

Создает делегат типа T с указанным целевым объектом из этого метода.

(Унаследовано от MethodInfo)
DefineParameter(Int32, ParameterAttributes, String)

Определяет параметр динамического метода.

Equals(Object)

Возвращает значение, указывающее, равен ли этот экземпляр указанному объекту.

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

Возвращает базовую реализацию для метода.

GetBaseDefinition()

При переопределении в производном классе возвращает MethodInfo объект для метода прямого или косвенного базового класса, в котором метод, представленный этим экземпляром, был впервые объявлен.

(Унаследовано от MethodInfo)
GetCustomAttributes(Boolean)

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

GetCustomAttributes(Type, Boolean)

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

GetCustomAttributesData()

Возвращает список CustomAttributeData объектов, представляющих данные о атрибутах, примененных к целевому элементу.

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

Возвращает объект DynamicILInfo, который можно использовать для создания текста метода из маркеров метаданных, областей и Microsoft потоков промежуточного языка (MSIL).

GetGenericArguments()

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

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

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

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

Возвращает хэш-код для этого экземпляра.

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

Возвращает генератор Microsoft промежуточного языка (MSIL) для метода с размером потока MSIL по умолчанию 64 байта.

GetILGenerator(Int32)

Возвращает генератор Microsoft промежуточного языка (MSIL) для метода с указанным размером потока MSIL.

GetMethodBody()

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

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

Возвращает флаги реализации для метода.

GetMethodImplementationFlags()

При переопределении в производном классе возвращает MethodImplAttributes флаги.

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

Возвращает параметры динамического метода.

HasSameMetadataDefinitionAs(MemberInfo)

Определяет и представляет динамический метод, который можно скомпилировать, выполнить и отменить. Удаленные методы доступны для сборки мусора.

(Унаследовано от MemberInfo)
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

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

IsDefined(Type, Boolean)

Указывает, определен ли указанный пользовательский тип атрибута.

MakeGenericMethod(Type[])

Заменяет элементы массива типов для параметров типа текущего определения универсального метода и возвращает MethodInfo объект, представляющий результирующий созданный метод.

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

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

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

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

Явные реализации интерфейса

Имя Описание
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

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

(Унаследовано от MemberInfo)
_MemberInfo.GetType()

Type Возвращает объект, MemberInfo представляющий класс.

(Унаследовано от MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

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

(Унаследовано от MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

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

(Унаследовано от MethodBase)
_MethodBase.GetType()

Описание этого элемента см. в разделе GetType().

(Унаследовано от MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

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

(Унаследовано от MethodBase)
_MethodBase.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от MethodBase)
_MethodBase.IsAbstract

Описание этого элемента см. в разделе IsAbstract.

(Унаследовано от MethodBase)
_MethodBase.IsAssembly

Описание этого элемента см. в разделе IsAssembly.

(Унаследовано от MethodBase)
_MethodBase.IsConstructor

Описание этого элемента см. в разделе IsConstructor.

(Унаследовано от MethodBase)
_MethodBase.IsFamily

Описание этого элемента см. в разделе IsFamily.

(Унаследовано от MethodBase)
_MethodBase.IsFamilyAndAssembly

Описание этого элемента см. в разделе IsFamilyAndAssembly.

(Унаследовано от MethodBase)
_MethodBase.IsFamilyOrAssembly

Описание этого элемента см. в разделе IsFamilyOrAssembly.

(Унаследовано от MethodBase)
_MethodBase.IsFinal

Описание этого элемента см. в разделе IsFinal.

(Унаследовано от MethodBase)
_MethodBase.IsHideBySig

Описание этого элемента см. в разделе IsHideBySig.

(Унаследовано от MethodBase)
_MethodBase.IsPrivate

Описание этого элемента см. в разделе IsPrivate.

(Унаследовано от MethodBase)
_MethodBase.IsPublic

Описание этого элемента см. в разделе IsPublic.

(Унаследовано от MethodBase)
_MethodBase.IsSpecialName

Описание этого элемента см. в разделе IsSpecialName.

(Унаследовано от MethodBase)
_MethodBase.IsStatic

Описание этого элемента см. в разделе IsStatic.

(Унаследовано от MethodBase)
_MethodBase.IsVirtual

Описание этого элемента см. в разделе IsVirtual.

(Унаследовано от MethodBase)
_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

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

(Унаследовано от MethodInfo)
_MethodInfo.GetType()

Предоставляет доступ к методу GetType() из COM.

(Унаследовано от MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

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

(Унаследовано от MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1).

(Унаследовано от MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к свойствам и методам, предоставляемым объектом.

(Унаследовано от MethodInfo)
ICustomAttributeProvider.GetCustomAttributes(Boolean)

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

(Унаследовано от MemberInfo)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

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

(Унаследовано от MemberInfo)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Указывает, определен ли один или несколько экземпляров attributeType этого элемента.

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

Методы расширения

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

Определяет и представляет динамический метод, который можно скомпилировать, выполнить и отменить. Удаленные методы доступны для сборки мусора.

GetCustomAttribute(MemberInfo, Type, Boolean)

Извлекает настраиваемый атрибут указанного типа, применяемого к указанному элементу, и при необходимости проверяет предки этого элемента.

GetCustomAttribute(MemberInfo, Type)

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

GetCustomAttribute<T>(MemberInfo, Boolean)

Извлекает настраиваемый атрибут указанного типа, применяемого к указанному элементу, и при необходимости проверяет предки этого элемента.

GetCustomAttribute<T>(MemberInfo)

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

GetCustomAttributes(MemberInfo, Boolean)

Извлекает коллекцию настраиваемых атрибутов, применяемых к указанному элементу, и при необходимости проверяет предки этого элемента.

GetCustomAttributes(MemberInfo, Type, Boolean)

Извлекает коллекцию настраиваемых атрибутов указанного типа, применяемого к указанному элементу, и при необходимости проверяет предки этого элемента.

GetCustomAttributes(MemberInfo, Type)

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

GetCustomAttributes(MemberInfo)

Извлекает коллекцию настраиваемых атрибутов, применяемых к указанному элементу.

GetCustomAttributes<T>(MemberInfo, Boolean)

Извлекает коллекцию настраиваемых атрибутов указанного типа, применяемого к указанному элементу, и при необходимости проверяет предки этого элемента.

GetCustomAttributes<T>(MemberInfo)

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

GetMetadataToken(MemberInfo)

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

GetRuntimeBaseDefinition(MethodInfo)

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

HasMetadataToken(MemberInfo)

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

IsDefined(MemberInfo, Type, Boolean)

Указывает, применяются ли пользовательские атрибуты указанного типа к указанному элементу и, при необходимости, применяются к его предкам.

IsDefined(MemberInfo, Type)

Указывает, применяются ли пользовательские атрибуты указанного типа к указанному элементу.

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

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