DynamicMethod Classe

Definição

Define e representa um método dinâmico que pode ser compilado, executado e descartado. Os métodos descartados estão disponíveis para coleta de lixo.

public ref class DynamicMethod sealed : System::Reflection::MethodInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : System.Reflection.MethodInfo
public sealed class DynamicMethod : System.Reflection.MethodInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
type DynamicMethod = class
    inherit MethodInfo
type DynamicMethod = class
    inherit MethodInfo
Public NotInheritable Class DynamicMethod
Inherits MethodInfo
Herança
Atributos

Exemplos

O exemplo de código a seguir cria um método dinâmico que usa dois parâmetros. O exemplo emite um corpo de função simples que imprime o primeiro parâmetro no console e o exemplo usa o segundo parâmetro como o valor retornado do método. O exemplo conclui o método criando um delegado, invoca o delegado com parâmetros diferentes e, por fim, invoca o método dinâmico usando o Invoke método.

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

Comentários

Para obter mais informações sobre essa API, consulte comentários da API Complementar para DynamicMethod.

Construtores

Nome Description
DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)

Cria um método dinâmico global para um módulo, especificando o nome do método, os atributos, a convenção de chamada, o tipo de retorno, os tipos de parâmetro, o módulo e se as verificações de visibilidade just-in-time (JIT) devem ser ignoradas para tipos e membros acessados pelo Microsoft MSIL (linguagem intermediária) do método dinâmico.

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

Cria um método dinâmico, especificando o nome do método, os atributos, a convenção de chamada, o tipo de retorno, os tipos de parâmetro, o tipo com o qual o método dinâmico está logicamente associado e se as verificações de visibilidade just-in-time (JIT) devem ser ignoradas para tipos e membros acessados pelo Microsoft MSIL (linguagem intermediária) do método dinâmico.

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

Inicializa um método dinâmico hospedado anonimamente, especificando o nome do método, o tipo de retorno, os tipos de parâmetro e se as verificações de visibilidade just-in-time (JIT) devem ser ignoradas para tipos e membros acessados pelo Microsoft MSIL (linguagem intermediária) do método dinâmico.

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

Cria um método dinâmico global para um módulo, especificando o nome do método, o tipo de retorno, os tipos de parâmetro, o módulo e se as verificações de visibilidade just-in-time (JIT) devem ser ignoradas para tipos e membros acessados pelo Microsoft MSIL (linguagem intermediária) do método dinâmico.

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

Cria um método dinâmico global para um módulo, especificando o nome do método, o tipo de retorno, os tipos de parâmetro e o módulo.

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

Cria um método dinâmico, especificando o nome do método, o tipo de retorno, os tipos de parâmetro, o tipo com o qual o método dinâmico está logicamente associado e se as verificações de visibilidade just-in-time (JIT) devem ser ignoradas para tipos e membros acessados pela linguagem intermediária Microsoft (MSIL) do método dinâmico.

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

Cria um método dinâmico, especificando o nome do método, o tipo de retorno, os tipos de parâmetro e o tipo com o qual o método dinâmico está logicamente associado.

DynamicMethod(String, Type, Type[])

Inicializa um método dinâmico hospedado anonimamente, especificando o nome do método, o tipo de retorno e os tipos de parâmetro.

Propriedades

Nome Description
Attributes

Obtém os atributos especificados quando o método dinâmico foi criado.

CallingConvention

Obtém a convenção de chamada especificada quando o método dinâmico foi criado.

ContainsGenericParameters

Obtém um valor que indica se um método genérico contém parâmetros de tipo genérico não atribuídos.

(Herdado de MethodInfo)
CustomAttributes

Obtém uma coleção que contém os atributos personalizados desse membro.

(Herdado de MemberInfo)
DeclaringType

Obtém o tipo que declara o método, que é sempre null para métodos dinâmicos.

InitLocals

Obtém ou define um valor que indica se as variáveis locais no método são inicializadas zero.

IsAbstract

Obtém um valor que indica se o método é abstrato.

(Herdado de MethodBase)
IsAssembly

Obtém um valor que indica se a visibilidade potencial desse método ou construtor é descrita por Assembly; ou seja, o método ou construtor é visível no máximo para outros tipos no mesmo assembly e não é visível para tipos derivados fora do assembly.

(Herdado de MethodBase)
IsConstructedGenericMethod

Define e representa um método dinâmico que pode ser compilado, executado e descartado. Os métodos descartados estão disponíveis para coleta de lixo.

(Herdado de MethodBase)
IsConstructor

Obtém um valor que indica se o método é um construtor.

(Herdado de MethodBase)
IsFamily

Obtém um valor que indica se a visibilidade desse método ou construtor é descrita por Family; ou seja, o método ou construtor é visível apenas dentro de sua classe e classes derivadas.

(Herdado de MethodBase)
IsFamilyAndAssembly

Obtém um valor que indica se a visibilidade desse método ou construtor é descrita por FamANDAssem; ou seja, o método ou construtor pode ser chamado por classes derivadas, mas somente se estiverem no mesmo assembly.

(Herdado de MethodBase)
IsFamilyOrAssembly

Obtém um valor que indica se a visibilidade potencial desse método ou construtor é descrita por FamORAssem; ou seja, o método ou construtor pode ser chamado por classes derivadas onde quer que estejam e por classes no mesmo assembly.

(Herdado de MethodBase)
IsFinal

Obtém um valor que indica se esse método é final.

(Herdado de MethodBase)
IsGenericMethod

Obtém um valor que indica se o método atual é um método genérico.

(Herdado de MethodInfo)
IsGenericMethodDefinition

Obtém um valor que indica se a corrente MethodInfo representa a definição de um método genérico.

(Herdado de MethodInfo)
IsHideBySig

Obtém um valor que indica se apenas um membro do mesmo tipo com exatamente a mesma assinatura está oculto na classe derivada.

(Herdado de MethodBase)
IsPrivate

Obtém um valor que indica se esse membro é privado.

(Herdado de MethodBase)
IsPublic

Obtém um valor que indica se esse é um método público.

(Herdado de MethodBase)
IsSecurityCritical

Obtém um valor que indica se o método dinâmico atual é crítico à segurança ou à segurança crítico e, portanto, pode executar operações críticas.

IsSecurityCritical

Obtém um valor que indica se o método ou construtor atual é crítico de segurança ou seguro-crítico no nível de confiança atual e, portanto, pode executar operações críticas.

(Herdado de MethodBase)
IsSecuritySafeCritical

Obtém um valor que indica se o método dinâmico atual é crítico de segurança no nível de confiança atual; ou seja, se ele pode executar operações críticas e pode ser acessado por código transparente.

IsSecuritySafeCritical

Obtém um valor que indica se o método ou construtor atual é crítico de segurança no nível de confiança atual; ou seja, se ele pode executar operações críticas e pode ser acessado por código transparente.

(Herdado de MethodBase)
IsSecurityTransparent

Obtém um valor que indica se o método dinâmico atual é transparente no nível de confiança atual e, portanto, não pode executar operações críticas.

IsSecurityTransparent

Obtém um valor que indica se o método ou construtor atual é transparente no nível de confiança atual e, portanto, não pode executar operações críticas.

(Herdado de MethodBase)
IsSpecialName

Obtém um valor que indica se esse método tem um nome especial.

(Herdado de MethodBase)
IsStatic

Obtém um valor que indica se o método é static.

(Herdado de MethodBase)
IsVirtual

Obtém um valor que indica se o método é virtual.

(Herdado de MethodBase)
MemberType

Obtém um MemberTypes valor que indica que esse membro é um método.

(Herdado de MethodInfo)
MetadataToken

Obtém um valor que identifica um elemento de metadados.

(Herdado de MemberInfo)
MethodHandle

Não há suporte para métodos dinâmicos.

MethodImplementationFlags

Obtém os MethodImplAttributes sinalizadores que especificam os atributos de uma implementação de método.

(Herdado de MethodBase)
Module

Obtém o módulo com o qual o método dinâmico está logicamente associado.

Module

Obtém o módulo no qual o tipo que declara o membro representado pela corrente MemberInfo é definido.

(Herdado de MemberInfo)
Name

Obtém o nome do método dinâmico.

ReflectedType

Obtém a classe que foi usada na reflexão para obter o método.

ReturnParameter

Obtém o parâmetro de retorno do método dinâmico.

ReturnType

Obtém o tipo de valor retornado para o método dinâmico.

ReturnTypeCustomAttributes

Obtém os atributos personalizados do tipo de retorno para o método dinâmico.

Métodos

Nome Description
CreateDelegate(Type, Object)

Conclui o método dinâmico e cria um delegado que pode ser usado para executá-lo, especificando o tipo delegado e um objeto ao qual o delegado está associado.

CreateDelegate(Type)

Conclui o método dinâmico e cria um delegado que pode ser usado para executá-lo.

DefineParameter(Int32, ParameterAttributes, String)

Define um parâmetro do método dinâmico.

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de MethodInfo)
GetBaseDefinition()

Retorna a implementação base para o método.

GetCustomAttributes(Boolean)

Retorna todos os atributos personalizados definidos para o método.

GetCustomAttributes(Type, Boolean)

Retorna os atributos personalizados do tipo especificado que foram aplicados ao método.

GetCustomAttributesData()

Retorna uma lista de CustomAttributeData objetos que representam dados sobre os atributos que foram aplicados ao membro de destino.

(Herdado de MemberInfo)
GetDynamicILInfo()

Retorna um objeto DynamicILInfo que pode ser usado para gerar um corpo do método a partir de tokens de metadados, escopos e fluxos de linguagem intermediária (MSIL) Microsoft.

GetGenericArguments()

Retorna uma matriz de Type objetos que representam os argumentos de tipo de um método genérico ou os parâmetros de tipo de uma definição de método genérico.

(Herdado de MethodInfo)
GetGenericMethodDefinition()

Retorna um MethodInfo objeto que representa uma definição de método genérico da qual o método atual pode ser construído.

(Herdado de MethodInfo)
GetHashCode()

Devolve o código hash para esta instância.

(Herdado de MethodInfo)
GetILGenerator()

Retorna um gerador msil (linguagem intermediária) Microsoft para o método com um tamanho de fluxo MSIL padrão de 64 bytes.

GetILGenerator(Int32)

Retorna um gerador msil (linguagem intermediária) Microsoft para o método com o tamanho do fluxo MSIL especificado.

GetMethodBody()

Quando substituído em uma classe derivada, obtém um MethodBody objeto que fornece acesso ao fluxo MSIL, variáveis locais e exceções para o método atual.

(Herdado de MethodBase)
GetMethodImplementationFlags()

Retorna os sinalizadores de implementação para o método.

GetParameters()

Retorna os parâmetros do método dinâmico.

HasSameMetadataDefinitionAs(MemberInfo)

Define e representa um método dinâmico que pode ser compilado, executado e descartado. Os métodos descartados estão disponíveis para coleta de lixo.

(Herdado de MemberInfo)
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Invoca o método dinâmico usando os parâmetros especificados, sob as restrições do associador especificado, com as informações de cultura especificadas.

IsDefined(Type, Boolean)

Indica se o tipo de atributo personalizado especificado está definido.

MakeGenericMethod(Type[])

Substitui os elementos de uma matriz de tipos para os parâmetros de tipo da definição de método genérico atual e retorna um MethodInfo objeto que representa o método construído resultante.

(Herdado de MethodInfo)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
ToString()

Retorna a assinatura do método, representada como uma cadeia de caracteres.

Implantações explícitas de interface

Nome Description
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de MemberInfo)
_MemberInfo.GetType()

Obtém um Type objeto que representa a MemberInfo classe.

(Herdado de MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.

(Herdado de MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de MethodBase)
_MethodBase.GetType()

Para obter uma descrição deste membro, consulte GetType().

(Herdado de MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.

(Herdado de MethodBase)
_MethodBase.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de MethodBase)
_MethodBase.IsAbstract

Para obter uma descrição deste membro, consulte IsAbstract.

(Herdado de MethodBase)
_MethodBase.IsAssembly

Para obter uma descrição deste membro, consulte IsAssembly.

(Herdado de MethodBase)
_MethodBase.IsConstructor

Para obter uma descrição deste membro, consulte IsConstructor.

(Herdado de MethodBase)
_MethodBase.IsFamily

Para obter uma descrição deste membro, consulte IsFamily.

(Herdado de MethodBase)
_MethodBase.IsFamilyAndAssembly

Para obter uma descrição deste membro, consulte IsFamilyAndAssembly.

(Herdado de MethodBase)
_MethodBase.IsFamilyOrAssembly

Para obter uma descrição deste membro, consulte IsFamilyOrAssembly.

(Herdado de MethodBase)
_MethodBase.IsFinal

Para obter uma descrição deste membro, consulte IsFinal.

(Herdado de MethodBase)
_MethodBase.IsHideBySig

Para obter uma descrição deste membro, consulte IsHideBySig.

(Herdado de MethodBase)
_MethodBase.IsPrivate

Para obter uma descrição deste membro, consulte IsPrivate.

(Herdado de MethodBase)
_MethodBase.IsPublic

Para obter uma descrição deste membro, consulte IsPublic.

(Herdado de MethodBase)
_MethodBase.IsSpecialName

Para obter uma descrição deste membro, consulte IsSpecialName.

(Herdado de MethodBase)
_MethodBase.IsStatic

Para obter uma descrição deste membro, consulte IsStatic.

(Herdado de MethodBase)
_MethodBase.IsVirtual

Para obter uma descrição deste membro, consulte IsVirtual.

(Herdado de MethodBase)
_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de MethodInfo)
_MethodInfo.GetType()

Fornece acesso ao método do GetType() COM.

(Herdado de MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo de um objeto, que podem ser usadas para obter as informações de tipo de uma interface.

(Herdado de MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de MethodInfo)

Métodos de Extensão

Nome Description
GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera um atributo personalizado de um tipo especificado que é aplicado a um membro especificado e, opcionalmente, inspeciona os ancestrais desse membro.

GetCustomAttribute(MemberInfo, Type)

Recupera um atributo personalizado de um tipo especificado que é aplicado a um membro especificado.

GetCustomAttribute<T>(MemberInfo, Boolean)

Recupera um atributo personalizado de um tipo especificado que é aplicado a um membro especificado e, opcionalmente, inspeciona os ancestrais desse membro.

GetCustomAttribute<T>(MemberInfo)

Recupera um atributo personalizado de um tipo especificado que é aplicado a um membro especificado.

GetCustomAttributes(MemberInfo, Boolean)

Recupera uma coleção de atributos personalizados que são aplicados a um membro especificado e, opcionalmente, inspeciona os ancestrais desse membro.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado e, opcionalmente, inspeciona os ancestrais desse membro.

GetCustomAttributes(MemberInfo, Type)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.

GetCustomAttributes(MemberInfo)

Recupera uma coleção de atributos personalizados que são aplicados a um membro especificado.

GetCustomAttributes<T>(MemberInfo, Boolean)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado e, opcionalmente, inspeciona os ancestrais desse membro.

GetCustomAttributes<T>(MemberInfo)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.

GetRuntimeBaseDefinition(MethodInfo)

Recupera um objeto que representa o método especificado na classe base direta ou indireta em que o método foi declarado pela primeira vez.

IsDefined(MemberInfo, Type, Boolean)

Indica se atributos personalizados de um tipo especificado são aplicados a um membro especificado e, opcionalmente, aplicados a seus ancestrais.

IsDefined(MemberInfo, Type)

Indica se atributos personalizados de um tipo especificado são aplicados a um membro especificado.

Aplica-se a

Confira também