DynamicMethod Classe

Définition

Définit et représente une méthode dynamique qui peut être compilée, exécutée et ignorée. Les méthodes ignorées sont disponibles pour le garbage collection.

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
Héritage
Attributs

Exemples

L’exemple de code suivant crée une méthode dynamique qui prend deux paramètres. L’exemple émet un corps de fonction simple qui imprime le premier paramètre dans la console, et l’exemple utilise le deuxième paramètre comme valeur de retour de la méthode. L’exemple complète la méthode en créant un délégué, appelle le délégué avec différents paramètres, puis appelle la méthode dynamique à l’aide de la Invoke méthode .

using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Globalization;

// Declare a delegate type that can be used to execute the completed
// dynamic method. 
private delegate int HelloDelegate(String^ msg, int ret);

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.
    array<Type^>^ helloArgs = { String::typeid, int::typeid };

    // 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 = gcnew DynamicMethod("Hello", 
        int::typeid, 
        helloArgs, 
        String::typeid->Module);

    // Create an array that specifies the parameter types of the
    // overload of Console::WriteLine to be used in Hello.
    array<Type^>^ writeStringArgs = { String::typeid };
    // Get the overload of Console::WriteLine that has one
    // String parameter.
    MethodInfo^ writeString = Console::typeid->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, nullptr);
    // 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(HelloDelegate::typeid);

    // 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.
    array<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(nullptr, BindingFlags::ExactBinding, nullptr, invokeArgs, gcnew 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 == nullptr)
    {
        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 == nullptr)
    {
        Console::WriteLine("\r\nReflectedType is null.");
    }
    else
    {
        Console::WriteLine("\r\nReflectedType: {0}", hello->ReflectedType);
    }

    if (hello->ReturnParameter == nullptr)
    {
        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 == Void::typeid)
    {
        Console::WriteLine("The method has no return type.");
    }
    else
    {
        ICustomAttributeProvider^ caProvider = hello->ReturnTypeCustomAttributes;
        array<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:");
            for each (Object^ attr in returnAttributes)
            {
                Console::WriteLine("\t{0}", attr->ToString());
            }
        }
    }

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

    // Display parameter information.
    array<ParameterInfo^>^ parameters = hello->GetParameters();
    Console::WriteLine("\r\nParameters: name, type, ParameterAttributes");
    for each (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
 */
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

Remarques

Pour plus d’informations sur cette API, consultez Remarques supplémentaires sur l’API pour DynamicMethod.

Constructeurs

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

Crée une méthode dynamique qui est globale pour un module, en spécifiant le nom de la méthode, les attributs, les conventions d'appel, le type de retour, les types de paramètres, le module et si les contrôles de visibilité juste-à-temps (JIT) doivent être ignorés pour les types et membres auxquels accède le langage Microsoft Intermediate Language (MSIL) de la méthode dynamique.

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

Crée une méthode dynamique, en spécifiant le nom de la méthode, les attributs, la convention d’appel, le type de retour, les types de paramètre, le type auquel la méthode dynamique est associée logiquement, et si les contrôles de visibilité juste-à-temps (JIT) doivent être ignorés pour les types et membres auxquels accède le langage MSIL (Microsoft Intermediate Language) de la méthode dynamique.

DynamicMethod(String, Type, Type[])

Initialise une méthode dynamique hébergée de manière anonyme, en spécifiant le nom de la méthode, le type de retour et les types de paramètres.

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

Initialise une méthode dynamique hébergée de façon anonyme, en spécifiant le nom de la méthode, le type de retour, les types de paramètre et si les contrôles de visibilité juste-à-temps (JIT) doivent être ignorés pour les types et membres auxquels accède le langage MSIL (Microsoft Intermediate Language) de la méthode dynamique.

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

Crée une méthode dynamique qui est globale pour un module, en spécifiant le nom de la méthode, le type de retour, les types de paramètres et le module.

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

Crée une méthode dynamique qui est globale pour un module, en spécifiant le nom de la méthode, le type de retour, les types de paramètre, le module et si les contrôles de visibilité juste-à-temps (JIT) doivent être ignorés pour les types et membres auxquels a accès le langage MSIL (Microsoft Intermediate Language) de la méthode dynamique.

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

Crée une méthode dynamique, en spécifiant le nom de la méthode, le type de retour, les types de paramètres et le type avec lequel la méthode dynamique est logiquement associée.

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

Crée une méthode dynamique, en spécifiant le nom de la méthode, le type de retour, les types de paramètre, le type auquel la méthode dynamique est associée logiquement, et si les contrôles de visibilité juste-à-temps (JIT) doivent être ignorés pour les types et membres auxquels accède le langage MSIL (Microsoft Intermediate Language) de la méthode dynamique.

Propriétés

Attributes

Obtient les attributs qui ont été spécifiés quand la méthode dynamique a été créée.

CallingConvention

Obtient la convention d’appel qui a été spécifiée quand la méthode dynamique a été créée.

ContainsGenericParameters

Obtient une valeur indiquant si une méthode générique contient des paramètres de type générique non attribués.

(Hérité de MethodInfo)
CustomAttributes

Obtient une collection qui contient les attributs personnalisés de ce membre.

(Hérité de MemberInfo)
DeclaringType

Obtient le type qui déclare la méthode, qui est toujours null pour les méthodes dynamiques.

InitLocals

Obtient ou définit une valeur qui indique si les variables locales de la méthode sont initialisées à zéro.

IsAbstract

Obtient une valeur indiquant si la méthode est abstraite.

(Hérité de MethodBase)
IsAssembly

Obtient une valeur indiquant si la visibilité potentielle de cette méthode ou de ce constructeur est décrite par Assembly, c'est-à-dire si la méthode ou le constructeur est visible au maximum par d'autres types du même assembly, et n'est pas visible par des types dérivés à l'extérieur de l'assembly.

(Hérité de MethodBase)
IsCollectible

Obtient une valeur qui indique si cet objet MemberInfo fait partie d’un assembly contenu dans un AssemblyLoadContext pouvant être collecté.

(Hérité de MemberInfo)
IsConstructedGenericMethod

Définit et représente une méthode dynamique qui peut être compilée, exécutée et ignorée. Les méthodes ignorées sont disponibles pour le garbage collection.

(Hérité de MethodBase)
IsConstructor

Obtient une valeur indiquant si la méthode est un constructeur.

(Hérité de MethodBase)
IsFamily

Obtient une valeur indiquant si la visibilité de cette méthode ou de ce constructeur est décrite par Family, c'est-à-dire si la méthode ou le constructeur est visible uniquement dans sa classe et dans ses classes dérivées.

(Hérité de MethodBase)
IsFamilyAndAssembly

Obtient une valeur indiquant si la visibilité de cette méthode ou de ce constructeur est décrite par FamANDAssem, c'est-à-dire si la méthode ou le constructeur peut être appelé par des classes dérivées, mais uniquement si elles se trouvent dans le même assembly.

(Hérité de MethodBase)
IsFamilyOrAssembly

Obtient une valeur indiquant si la visibilité potentielle de cette méthode ou de ce constructeur est décrite par FamORAssem, c'est-à-dire si la méthode ou le constructeur peut être appelé par des classes dérivées où qu'elles se trouvent, et par des classes du même assembly.

(Hérité de MethodBase)
IsFinal

Obtient une valeur indiquant si cette méthode est final.

(Hérité de MethodBase)
IsGenericMethod

Obtient une valeur indiquant si la méthode actuelle est une méthode générique.

(Hérité de MethodInfo)
IsGenericMethodDefinition

Obtient une valeur indiquant si le MethodInfo actuel représente la définition d'une méthode générique.

(Hérité de MethodInfo)
IsHideBySig

Obtient une valeur indiquant si seul un membre du même type, doté d'une signature identique, est caché dans la classe dérivée.

(Hérité de MethodBase)
IsPrivate

Obtient une valeur indiquant si ce membre est privé.

(Hérité de MethodBase)
IsPublic

Obtient une valeur indiquant s'il s'agit d'une méthode publique.

(Hérité de MethodBase)
IsSecurityCritical

Obtient une valeur qui indique si la méthode dynamique actuelle est critique de sécurité (security-critical) ou critique sécurisée (security-safe-critical), et peut donc effectuer des opérations critiques.

IsSecurityCritical

Obtient une valeur qui indique si la méthode ou le constructeur actuel est critique de sécurité (security-critical) ou critique sécurisé (security-safe-critical) au niveau de confiance actuel et peut par conséquent exécuter des opérations critiques.

(Hérité de MethodBase)
IsSecuritySafeCritical

Obtient une valeur qui indique si la méthode dynamique actuelle est critique sécurisée au niveau de confiance actuel, autrement dit si elle peut exécuter des opérations critiques et être accessible par du code transparent.

IsSecuritySafeCritical

Obtient une valeur qui indique si la méthode ou le constructeur actuel est critique sécurisé au niveau de confiance actuel ; autrement dit, si la méthode ou le constructeur peut exécuter des opérations critiques et être accessible par du code transparent.

(Hérité de MethodBase)
IsSecurityTransparent

Obtient une valeur qui indique si la méthode dynamique actuelle est transparente au niveau de confiance actuel et ne peut donc pas exécuter d’opérations critiques.

IsSecurityTransparent

Obtient une valeur qui indique si la méthode ou le constructeur actuel est transparent au niveau de confiance actuel et ne peut par conséquent pas exécuter d'opérations critiques.

(Hérité de MethodBase)
IsSpecialName

Obtient une valeur indiquant si cette méthode est dotée d'un nom spécial.

(Hérité de MethodBase)
IsStatic

Obtient une valeur indiquant si la méthode est static.

(Hérité de MethodBase)
IsVirtual

Obtient une valeur indiquant si la méthode est virtual.

(Hérité de MethodBase)
MemberType

Obtient une MemberTypes valeur indiquant que ce membre est une méthode.

(Hérité de MethodInfo)
MetadataToken

Obtient une valeur qui identifie un élément de métadonnées.

(Hérité de MemberInfo)
MethodHandle

Non pris en charge pour les méthodes dynamiques.

MethodHandle

Obtient un handle vers la représentation interne des métadonnées d'une méthode.

(Hérité de MethodBase)
MethodImplementationFlags

Définit et représente une méthode dynamique qui peut être compilée, exécutée et ignorée. Les méthodes ignorées sont disponibles pour le garbage collection.

MethodImplementationFlags

Obtient les indicateurs MethodImplAttributes qui spécifient les attributs de l'implémentation d'une méthode.

(Hérité de MethodBase)
Module

Obtient le module auquel la méthode dynamique est logiquement associée.

Module

Obtient le module dans lequel le type qui déclare le membre représenté par le MemberInfo actuel est défini.

(Hérité de MemberInfo)
Name

Obtient le nom de la méthode dynamique.

ReflectedType

Obtient la classe qui a été utilisée dans la réflexion pour obtenir la méthode.

ReflectedType

Obtient l'objet classe utilisé pour obtenir cette instance de MemberInfo.

(Hérité de MemberInfo)
ReturnParameter

Obtient le paramètre de retour de la méthode dynamique.

ReturnType

Obtient le type de la valeur de retour de la méthode dynamique.

ReturnTypeCustomAttributes

Obtient les attributs personnalisés du type de retour pour la méthode dynamique.

ReturnTypeCustomAttributes

Obtient les attributs personnalisés du type de retour.

(Hérité de MethodInfo)

Méthodes

CreateDelegate(Type)

Exécute la méthode dynamique et crée un délégué qui peut être utilisé pour l’exécuter.

CreateDelegate(Type, Object)

Exécute la méthode dynamique et crée un délégué qui peut être utilisé pour l’exécuter, en spécifiant le type de délégué et un objet auquel le délégué est lié.

CreateDelegate<T>()

Crée un délégué de type T à partir de cette méthode.

(Hérité de MethodInfo)
CreateDelegate<T>(Object)

Crée un délégué de type T avec la cible spécifiée à partir de cette méthode.

(Hérité de MethodInfo)
DefineParameter(Int32, ParameterAttributes, String)

Définit un paramètre de la méthode dynamique.

Equals(Object)

Retourne une valeur qui indique si cette instance est égale à un objet spécifié.

(Hérité de MethodInfo)
GetBaseDefinition()

Retourne l’implémentation de base pour la méthode.

GetBaseDefinition()

En cas de substitution dans une classe dérivée, retourne l'objet MethodInfo pour la méthode sur la classe de base directe ou indirecte dans laquelle la méthode représentée par cette instance a été déclarée initialement.

(Hérité de MethodInfo)
GetCustomAttributes(Boolean)

Retourne tous les attributs personnalisés définis pour cette méthode.

GetCustomAttributes(Boolean)

En cas de substitution dans une classe dérivée, retourne un tableau de tous les attributs personnalisés appliqués à ce membre.

(Hérité de MemberInfo)
GetCustomAttributes(Type, Boolean)

Retourne les attributs personnalisés du type spécifié qui ont été appliqués à la méthode.

GetCustomAttributes(Type, Boolean)

En cas de substitution dans une classe dérivée, retourne un tableau d’attributs personnalisés appliqués à ce membre et identifiés par Type.

(Hérité de MemberInfo)
GetCustomAttributesData()

Renvoie une liste d’objets CustomAttributeData représentant des données sur les attributs qui ont été appliqués au membre cible.

(Hérité de MemberInfo)
GetDynamicILInfo()

Retourne un objet DynamicILInfo qui peut être utilisé pour générer un corps de méthode à partir de jetons de métadonnées, de portées et de flux MSIL (Microsoft Intermediate Language).

GetGenericArguments()

Retourne un tableau d'objets Type qui représentent les arguments de type d'une méthode générique ou les paramètres de type d'une définition de méthode générique.

(Hérité de MethodInfo)
GetGenericMethodDefinition()

Retourne un objet MethodInfo qui représente une définition de méthode générique à partir de laquelle la méthode actuelle peut être construite.

(Hérité de MethodInfo)
GetHashCode()

Retourne le code de hachage de cette instance.

(Hérité de MethodInfo)
GetILGenerator()

Retourne un générateur de langage MSIL (Microsoft Intermediate Language) pour la méthode avec une taille de flux MSIL par défaut de 64 bits.

GetILGenerator(Int32)

Retourne un générateur de langage MSIL (Microsoft Intermediate Language) pour la méthode avec la taille de flux MSIL spécifiée.

GetMethodBody()

En cas de substitution dans une classe dérivée, obtient un objet MethodBody qui donne accès au flux MSIL, aux variables locales et aux exceptions pour la méthode actuelle.

(Hérité de MethodBase)
GetMethodImplementationFlags()

Retourne les indicateurs d’implémentation pour la méthode.

GetMethodImplementationFlags()

Lors du remplacement dans une classe dérivée, retourne les indicateurs MethodImplAttributes.

(Hérité de MethodBase)
GetParameters()

Retourne les paramètres de la méthode dynamique.

GetType()

Identifie les attributs d'une méthode et donne accès aux métadonnées de la méthode.

(Hérité de MethodInfo)
HasSameMetadataDefinitionAs(MemberInfo)

Définit et représente une méthode dynamique qui peut être compilée, exécutée et ignorée. Les méthodes ignorées sont disponibles pour le garbage collection.

(Hérité de MemberInfo)
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Appelle la méthode dynamique à l’aide des paramètres spécifiés, sous les contraintes du binder spécifié, avec les informations de culture spécifiées.

Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

En cas de substitution dans une classe dérivée, appelle la méthode ou le constructeur réfléchi avec les paramètres donnés.

(Hérité de MethodBase)
Invoke(Object, Object[])

Appelle la méthode ou le constructeur représenté par l’instance actuelle, selon les paramètres spécifiés.

(Hérité de MethodInfo)
IsDefined(Type, Boolean)

Indique si le type d’attribut personnalisé spécifié est défini.

IsDefined(Type, Boolean)

En cas de substitution dans une classe dérivée, indique si un ou plusieurs attributs du type spécifié ou de ses types dérivés sont appliqués à ce membre.

(Hérité de MemberInfo)
MakeGenericMethod(Type[])

Substitue les éléments d'un tableau de types aux paramètres de type de la définition de méthode générique actuelle et retourne un objet MethodInfo représentant la méthode construite résultante.

(Hérité de MethodInfo)
MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
ToString()

Retourne la signature de la méthode, représentée sous forme de chaîne.

Implémentations d’interfaces explicites

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

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.

(Hérité de MemberInfo)
_MemberInfo.GetType()

Obtient un objet Type représentant la classe MemberInfo.

(Hérité de MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface.

(Hérité de MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).

(Hérité de MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fournit l'accès aux propriétés et aux méthodes exposées par un objet.

(Hérité de MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.

(Hérité de MethodBase)
_MethodBase.GetType()

Pour obtenir une description de ce membre, consultez GetType().

(Hérité de MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type pour un objet, qui peuvent être utilisées ensuite pour obtenir les informations de type d'une interface.

(Hérité de MethodBase)
_MethodBase.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).

(Hérité de MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fournit l'accès aux propriétés et aux méthodes exposées par un objet.

(Hérité de MethodBase)
_MethodBase.IsAbstract

Pour obtenir une description de ce membre, consultez IsAbstract.

(Hérité de MethodBase)
_MethodBase.IsAssembly

Pour obtenir une description de ce membre, consultez IsAssembly.

(Hérité de MethodBase)
_MethodBase.IsConstructor

Pour obtenir une description de ce membre, consultez IsConstructor.

(Hérité de MethodBase)
_MethodBase.IsFamily

Pour obtenir une description de ce membre, consultez IsFamily.

(Hérité de MethodBase)
_MethodBase.IsFamilyAndAssembly

Pour obtenir une description de ce membre, consultez IsFamilyAndAssembly.

(Hérité de MethodBase)
_MethodBase.IsFamilyOrAssembly

Pour obtenir une description de ce membre, consultez IsFamilyOrAssembly.

(Hérité de MethodBase)
_MethodBase.IsFinal

Pour obtenir une description de ce membre, consultez IsFinal.

(Hérité de MethodBase)
_MethodBase.IsHideBySig

Pour obtenir une description de ce membre, consultez IsHideBySig.

(Hérité de MethodBase)
_MethodBase.IsPrivate

Pour obtenir une description de ce membre, consultez IsPrivate.

(Hérité de MethodBase)
_MethodBase.IsPublic

Pour obtenir une description de ce membre, consultez IsPublic.

(Hérité de MethodBase)
_MethodBase.IsSpecialName

Pour obtenir une description de ce membre, consultez IsSpecialName.

(Hérité de MethodBase)
_MethodBase.IsStatic

Pour obtenir une description de ce membre, consultez IsStatic.

(Hérité de MethodBase)
_MethodBase.IsVirtual

Pour obtenir une description de ce membre, consultez IsVirtual.

(Hérité de MethodBase)
_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.

(Hérité de MethodInfo)
_MethodInfo.GetType()

Fournit l'accès à la méthode GetType() à partir de COM.

(Hérité de MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type pour un objet, qui peuvent être utilisées pour obtenir les informations de type d'une interface.

(Hérité de MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).

(Hérité de MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fournit l'accès aux propriétés et aux méthodes exposées par un objet.

(Hérité de MethodInfo)
ICustomAttributeProvider.GetCustomAttributes(Boolean)

Retourne un tableau de tous les attributs personnalisés définis sur ce membre, en dehors des attributs nommés, ou un tableau vide s’il n’y a aucun attribut personnalisé.

(Hérité de MemberInfo)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

Retourne un tableau d’attributs personnalisés définis sur ce membre, identifiés par type, ou un tableau vide s’il n’y a aucun attribut personnalisé de ce type.

(Hérité de MemberInfo)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Indique si une ou plusieurs instances de attributeType sont définies sur ce membre.

(Hérité de MemberInfo)

Méthodes d’extension

GetCustomAttribute(MemberInfo, Type)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un membre spécifié.

GetCustomAttribute(MemberInfo, Type, Boolean)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un membre spécifié, et inspecte éventuellement les ancêtres de ce membre.

GetCustomAttribute<T>(MemberInfo)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un membre spécifié.

GetCustomAttribute<T>(MemberInfo, Boolean)

Récupère un attribut personnalisé d'un type spécifié qui est appliqué à un membre spécifié, et inspecte éventuellement les ancêtres de ce membre.

GetCustomAttributes(MemberInfo)

Récupère une collection d'attributs personnalisés qui sont appliqués à un membre spécifié.

GetCustomAttributes(MemberInfo, Boolean)

Récupère une collection d'attributs personnalisés qui sont appliqués à un membre spécifié, et inspecte éventuellement les ancêtres de ce membre.

GetCustomAttributes(MemberInfo, Type)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un membre spécifié.

GetCustomAttributes(MemberInfo, Type, Boolean)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un membre spécifié, et inspecte éventuellement les ancêtres de ce membre.

GetCustomAttributes<T>(MemberInfo)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un membre spécifié.

GetCustomAttributes<T>(MemberInfo, Boolean)

Extrait une collection d'attributs personnalisés d'un type spécifié qui sont appliqués à un membre spécifié, et inspecte éventuellement les ancêtres de ce membre.

IsDefined(MemberInfo, Type)

Indique si des attributs personnalisés d'un type spécifié sont appliqués à un membre spécifié.

IsDefined(MemberInfo, Type, Boolean)

Indique si les attributs personnalisés d'un type spécifié sont appliqués à un membre spécifié, et, éventuellement, appliqués à ses ancêtres.

GetMetadataToken(MemberInfo)

Obtient un jeton de métadonnées pour le membre donné, s’il est disponible.

HasMetadataToken(MemberInfo)

Retourne une valeur qui indique si un jeton de métadonnées est disponible pour le membre spécifié.

GetBaseDefinition(MethodInfo)

Définit et représente une méthode dynamique qui peut être compilée, exécutée et ignorée. Les méthodes ignorées sont disponibles pour le garbage collection.

GetRuntimeBaseDefinition(MethodInfo)

Récupère un objet qui représente la méthode spécifiée dans la classe de base directe ou indirecte où la méthode a été déclarée la première fois.

S’applique à

Voir aussi