DynamicMethod Classe

Definizione

Definisce e rappresenta un metodo dinamico che può essere compilato, eseguito e annullato. I metodi annullati possono essere sottoposti a 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
Ereditarietà
Attributi

Esempio

Nell'esempio di codice seguente viene creato un metodo dinamico che accetta due parametri. Nell'esempio viene generato un corpo di funzione semplice che stampa il primo parametro nella console e nell'esempio viene usato il secondo parametro come valore restituito del metodo . L'esempio completa il metodo creando un delegato, richiama il delegato con parametri diversi e infine richiama il metodo dinamico usando il Invoke metodo .

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

Commenti

Per altre informazioni su questa API, vedere Note sulle API supplementari per DynamicMethod.

Costruttori

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

Crea un metodo dinamico globale per un metodo, specificando il nome del metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametro, il modulo e se i controlli di visibilità JIT possono essere ignorati per i tipi e i membri cui accede il linguaggio MSIL (Microsoft Intermediate Language) del metodo dinamico.

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

Crea un metodo dinamico, specificando il nome del metodo, gli attributi, la convenzione di chiamata, il tipo restituito, i tipi di parametro, il tipo a cui il metodo dinamico è associato in modo logico e se i controlli di visibilità JIT possono essere ignorati per i tipi e i membri cui accede il linguaggio MSIL (Microsoft Intermediate Language) del metodo dinamico.

DynamicMethod(String, Type, Type[])

Inizializza un metodo dinamico ospitato anonimamente, specificando il nome del metodo, il tipo restituito e i tipi di parametro.

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

Inizializza un metodo dinamico ospitato anonimamente, specificando il nome del metodo, il tipo restituito, i tipi di parametro e se i controlli di visibilità JIT possono essere ignorati per i tipi e i membri cui accede il linguaggio MSIL (Microsoft Intermediate Language) del metodo dinamico.

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

Crea un metodo dinamico che è globale per un modulo, specificando il nome del metodo, il tipo restituito, i tipi di parametro e il modulo.

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

Crea un metodo dinamico globale per un modulo, specificando il nome del metodo, il tipo restituito, i tipi di parametri e il modulo e indicando se deve essere ignorato il controllo di visibilità JIT per i tipi e i membri del metodo dinamico a cui accede MSIL (Microsoft Intermediate Language).

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

Crea un metodo dinamico, specificando il nome del metodo, il tipo restituito, i parametri di tipo e il tipo a cui il metodo dinamico è associato dal punto di vista logico.

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

Crea un metodo dinamico, specificando il nome del metodo, il tipo restituito, i tipi di parametro, il tipo a cui il metodo dinamico è associato in modo logico e se i controlli di visibilità JIT possono essere ignorati per i tipi e i membri cui accede il linguaggio MSIL (Microsoft Intermediate Language) del metodo dinamico.

Proprietà

Attributes

Ottiene gli attributi specificati quando il metodo dinamico è stato creato.

CallingConvention

Ottiene la convenzione di chiamata specificata durante la creazione del metodo dinamico.

ContainsGenericParameters

Ottiene un valore che indica se un metodo generico contiene parametri di tipo generico non assegnati.

(Ereditato da MethodInfo)
CustomAttributes

Ottiene una raccolta che contiene gli attributi personalizzati del membro.

(Ereditato da MemberInfo)
DeclaringType

Ottiene il tipo che dichiara il metodo, che è sempre null per i metodi dinamici.

InitLocals

Ottiene o imposta un valore che indica se le variabili locali nel metodo sono inizializzate su zero.

IsAbstract

Ottiene un valore che indica se il metodo è astratto.

(Ereditato da MethodBase)
IsAssembly

Ottiene un valore che indica se la visibilità potenziale di questo metodo o costruttore è descritta da Assembly, ovvero se il metodo o costruttore è visibile al massimo ad altri tipi dello stesso assembly, ma non ai tipi derivati all'esterno dell'assembly.

(Ereditato da MethodBase)
IsCollectible

Ottiene un valore che indica se questo oggetto MemberInfo fa parte di un assembly conservato in un AssemblyLoadContext ritirabile.

(Ereditato da MemberInfo)
IsConstructedGenericMethod

Definisce e rappresenta un metodo dinamico che può essere compilato, eseguito e annullato. I metodi annullati possono essere sottoposti a Garbage Collection.

(Ereditato da MethodBase)
IsConstructor

Ottiene un valore che indica se il metodo è un costruttore.

(Ereditato da MethodBase)
IsFamily

Ottiene un valore che indica se la visibilità di questo metodo o costruttore è descritta da Family, ovvero se il metodo o costruttore è visibile solo all'interno della relativa classe e delle classi derivate.

(Ereditato da MethodBase)
IsFamilyAndAssembly

Ottiene un valore che indica se la visibilità di questo metodo o costruttore è descritta da FamANDAssem, ovvero se è possibile chiamare il metodo o il costruttore da classi derivate, ma solo se appartenenti allo stesso assembly.

(Ereditato da MethodBase)
IsFamilyOrAssembly

Ottiene un valore che indica se la visibilità potenziale di questo metodo o costruttore è descritta da FamORAssem, ovvero se è possibile chiamare il metodo o il costruttore da classi derivate indipendentemente dalla posizione e da classi appartenenti allo stesso assembly.

(Ereditato da MethodBase)
IsFinal

Ottiene un valore che indica se il metodo è final.

(Ereditato da MethodBase)
IsGenericMethod

Ottiene un valore che indica se il metodo corrente è un metodo generico.

(Ereditato da MethodInfo)
IsGenericMethodDefinition

Ottiene un valore che indica se la classe MethodInfo corrente rappresenta la definizione di un metodo generico.

(Ereditato da MethodInfo)
IsHideBySig

Ottiene un valore che indica se nella classe derivata è nascosto un solo membro dello stesso tipo che riporta esattamente la stessa firma.

(Ereditato da MethodBase)
IsPrivate

Ottiene un valore che indica se questo membro è privato.

(Ereditato da MethodBase)
IsPublic

Ottiene un valore che indica se si tratta di un metodo pubblico.

(Ereditato da MethodBase)
IsSecurityCritical

Ottiene un valore che indica se il metodo dinamico corrente è critico per la sicurezza o critico per la sicurezza e richiamabile da codice trasparente e può pertanto eseguire operazioni critiche.

IsSecurityCritical

Ottiene un valore che indica se il metodo o il costruttore corrente è critico per la sicurezza o security-safe-critical al livello di attendibilità corrente, e pertanto può eseguire operazioni critiche.

(Ereditato da MethodBase)
IsSecuritySafeCritical

Ottiene un valore che indica se il metodo dinamico corrente è critico per la sicurezza al livello di attendibilità corrente, vale a dire se può eseguire operazioni critiche e se è possibile accedervi tramite codice trasparente.

IsSecuritySafeCritical

Ottiene un valore che indica se il metodo o il costruttore corrente è security-safe-critical al livello di attendibilità corrente, vale a dire se può eseguire operazioni critiche ed essere richiamato da codice trasparente.

(Ereditato da MethodBase)
IsSecurityTransparent

Ottiene un valore che indica se il metodo dinamico corrente è trasparente al livello di attendibilità corrente e pertanto non può eseguire operazioni critiche.

IsSecurityTransparent

Ottiene un valore che indica se il metodo o il costruttore corrente è trasparente al livello di attendibilità corrente, e pertanto non può eseguire operazioni critiche.

(Ereditato da MethodBase)
IsSpecialName

Ottiene un valore che indica se questo metodo ha un nome speciale.

(Ereditato da MethodBase)
IsStatic

Ottiene un valore che indica se il metodo è static.

(Ereditato da MethodBase)
IsVirtual

Ottiene un valore che indica se il metodo è virtual.

(Ereditato da MethodBase)
MemberType

Ottiene un valore MemberTypes che indica che questo membro è un metodo.

(Ereditato da MethodInfo)
MetadataToken

Ottiene un valore che identifica un elemento di metadati.

(Ereditato da MemberInfo)
MethodHandle

Non supportato per metodi dinamici.

MethodHandle

Ottiene un handle alla rappresentazione interna dei metadati di un metodo.

(Ereditato da MethodBase)
MethodImplementationFlags

Definisce e rappresenta un metodo dinamico che può essere compilato, eseguito e annullato. I metodi annullati possono essere sottoposti a Garbage Collection.

MethodImplementationFlags

Ottiene i flag MethodImplAttributes che specificano gli attributi di implementazione di un metodo.

(Ereditato da MethodBase)
Module

Ottiene il modulo a cui il metodo dinamico è associato in modo logico.

Module

Ottiene il modulo in cui viene definito il tipo che dichiara il membro rappresentato dall'oggetto MemberInfo corrente.

(Ereditato da MemberInfo)
Name

Ottiene il nome del metodo dinamico.

ReflectedType

Ottiene la classe usata nella reflection per ottenere il metodo.

ReflectedType

Ottiene l'oggetto classe utilizzato per ottenere questa istanza di MemberInfo.

(Ereditato da MemberInfo)
ReturnParameter

Ottiene il parametro restituito del metodo dinamico.

ReturnType

Ottiene il tipo di valore restituito per il metodo dinamico.

ReturnTypeCustomAttributes

Ottiene gli attributi personalizzati del tipo restituito per il metodo dinamico.

ReturnTypeCustomAttributes

Ottiene gli attributi personalizzati per il tipo restituito.

(Ereditato da MethodInfo)

Metodi

CreateDelegate(Type)

Completa il metodo dinamico e crea un delegato che può essere usato per eseguirlo.

CreateDelegate(Type, Object)

Completa il metodo dinamico e crea un delegato che può essere usato per eseguirlo, specificando il tipo di delegato e l'oggetto a cui il delegato è associato.

CreateDelegate<T>()

Crea un delegato di tipo T da questo metodo.

(Ereditato da MethodInfo)
CreateDelegate<T>(Object)

Crea un delegato di tipo T con la destinazione specificata da questo metodo.

(Ereditato da MethodInfo)
DefineParameter(Int32, ParameterAttributes, String)

Definisce un parametro del metodo dinamico.

Equals(Object)

Restituisce un valore che indica se questa istanza è uguale a un oggetto specificato.

(Ereditato da MethodInfo)
GetBaseDefinition()

Restituisce l'implementazione di base per il metodo.

GetBaseDefinition()

Quando ne viene eseguito l'override in una classe derivata,, restituisce l'oggetto MethodInfo relativo al metodo presente nella classe base diretta o indiretta in cui il metodo rappresentato da questa istanza è stato inizialmente dichiarato.

(Ereditato da MethodInfo)
GetCustomAttributes(Boolean)

Restituisce tutti gli attributi personalizzati definiti per il metodo.

GetCustomAttributes(Boolean)

Se sottoposto a override in una classe derivata, restituisce una matrice di tutti gli attributi personalizzati applicati a questo membro.

(Ereditato da MemberInfo)
GetCustomAttributes(Type, Boolean)

Restituisce gli attributi personalizzati del tipo specificato che sono stati applicati al metodo.

GetCustomAttributes(Type, Boolean)

Quando viene sottoposto a override in una classe derivata, questo metodo restituisce una matrice di attributi personalizzati applicati a questo membro e identificati da Type.

(Ereditato da MemberInfo)
GetCustomAttributesData()

Restituisce un elenco di oggetti CustomAttributeData che rappresentano i dati relativi agli attributi applicati al membro di destinazione.

(Ereditato da MemberInfo)
GetDynamicILInfo()

Restituisce un oggetto DynamicILInfo che può essere usato per generare un corpo del metodo dai token di metadati, ambiti e flussi MSIL (Microsoft Intermediate Language).

GetGenericArguments()

Restituisce una matrice di oggetti Type che rappresentano gli argomenti tipo di un metodo generico o i parametri di tipo della definizione di un metodo generico.

(Ereditato da MethodInfo)
GetGenericMethodDefinition()

Restituisce un oggetto MethodInfo che rappresenta la definizione di un metodo generica da cui è possibile costruire il metodo corrente.

(Ereditato da MethodInfo)
GetHashCode()

Restituisce il codice hash per l'istanza.

(Ereditato da MethodInfo)
GetILGenerator()

Restituisce un generatore di Microsoft Intermediate Language (MSIL) per il metodo con una dimensione di flusso MSIL predefinita di 64 byte.

GetILGenerator(Int32)

Restituisce un generatore di Microsoft Intermediate Language (MSIL) per il metodo con le dimensioni del flusso MSIL specificate.

GetMethodBody()

Se viene eseguito l'override in una classe derivata, ottiene un oggetto MethodBody che consente di accedere al flusso MSIL, alle variabili locali e alle eccezioni per il metodo corrente.

(Ereditato da MethodBase)
GetMethodImplementationFlags()

Restituisce i flag di implementazione per il metodo.

GetMethodImplementationFlags()

Quando è sottoposto a override in una classe derivata, restituisce i flag MethodImplAttributes.

(Ereditato da MethodBase)
GetParameters()

Restituisce i parametri del metodo dinamico.

GetType()

Individua gli attributi di un metodo e consente di accedere ai relativi metadati.

(Ereditato da MethodInfo)
HasSameMetadataDefinitionAs(MemberInfo)

Definisce e rappresenta un metodo dinamico che può essere compilato, eseguito e annullato. I metodi annullati possono essere sottoposti a Garbage Collection.

(Ereditato da MemberInfo)
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

Richiama il metodo dinamico usando i parametri specificati, con i vincoli del binder specificato e le informazioni sulle impostazioni cultura specificate.

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

Quando viene sottoposto a override in una classe derivata, richiama il metodo o il costruttore ottenuto mediante reflection con i parametri specificati.

(Ereditato da MethodBase)
Invoke(Object, Object[])

Richiama il metodo o il costruttore rappresentato dall'istanza corrente usando i parametri specificati.

(Ereditato da MethodInfo)
IsDefined(Type, Boolean)

Indica se il tipo di attributo personalizzato specificato è definito.

IsDefined(Type, Boolean)

Quando se ne effettua l'override in una classe derivata, indica se a questo membro sono applicati uno o più attributi del tipo specificato o dei tipi derivati.

(Ereditato da MemberInfo)
MakeGenericMethod(Type[])

Sostituisce con gli elementi di una matrice di tipi i parametri di tipo della definizione di metodo generica corrente e restituisce un oggetto MethodInfo che rappresenta il metodo costruito risultante.

(Ereditato da MethodInfo)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Restituisce la firma del metodo, rappresentata come stringa.

Implementazioni dell'interfaccia esplicita

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

Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch.

(Ereditato da MemberInfo)
_MemberInfo.GetType()

Ottiene un oggetto Type che rappresenta la classe MemberInfo.

(Ereditato da MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo relative a un oggetto che può quindi essere usato per ottenere informazioni sul tipo relative a un'interfaccia.

(Ereditato da MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).

(Ereditato da MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso a proprietà e metodi esposti da un oggetto.

(Ereditato da MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch.

(Ereditato da MethodBase)
_MethodBase.GetType()

Per una descrizione di questo membro, vedere GetType().

(Ereditato da MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo relative a un oggetto che può quindi essere usato per ottenere informazioni sul tipo relative a un'interfaccia.

(Ereditato da MethodBase)
_MethodBase.GetTypeInfoCount(UInt32)

Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).

(Ereditato da MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso a proprietà e metodi esposti da un oggetto.

(Ereditato da MethodBase)
_MethodBase.IsAbstract

Per una descrizione di questo membro, vedere IsAbstract.

(Ereditato da MethodBase)
_MethodBase.IsAssembly

Per una descrizione di questo membro, vedere IsAssembly.

(Ereditato da MethodBase)
_MethodBase.IsConstructor

Per una descrizione di questo membro, vedere IsConstructor.

(Ereditato da MethodBase)
_MethodBase.IsFamily

Per una descrizione di questo membro, vedere IsFamily.

(Ereditato da MethodBase)
_MethodBase.IsFamilyAndAssembly

Per una descrizione di questo membro, vedere IsFamilyAndAssembly.

(Ereditato da MethodBase)
_MethodBase.IsFamilyOrAssembly

Per una descrizione di questo membro, vedere IsFamilyOrAssembly.

(Ereditato da MethodBase)
_MethodBase.IsFinal

Per una descrizione di questo membro, vedere IsFinal.

(Ereditato da MethodBase)
_MethodBase.IsHideBySig

Per una descrizione di questo membro, vedere IsHideBySig.

(Ereditato da MethodBase)
_MethodBase.IsPrivate

Per una descrizione di questo membro, vedere IsPrivate.

(Ereditato da MethodBase)
_MethodBase.IsPublic

Per una descrizione di questo membro, vedere IsPublic.

(Ereditato da MethodBase)
_MethodBase.IsSpecialName

Per una descrizione di questo membro, vedere IsSpecialName.

(Ereditato da MethodBase)
_MethodBase.IsStatic

Per una descrizione di questo membro, vedere IsStatic.

(Ereditato da MethodBase)
_MethodBase.IsVirtual

Per una descrizione di questo membro, vedere IsVirtual.

(Ereditato da MethodBase)
_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Esegue il mapping di un set di nomi a un set corrispondente di ID dispatch.

(Ereditato da MethodInfo)
_MethodInfo.GetType()

Fornisce l'accesso al metodo GetType() da COM.

(Ereditato da MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera le informazioni sul tipo relative a un oggetto, che possono essere usate per ottenere informazioni sul tipo relative a un'interfaccia.

(Ereditato da MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32)

Recupera il numero delle interfacce di informazioni sul tipo fornite da un oggetto (0 o 1).

(Ereditato da MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornisce l'accesso a proprietà e metodi esposti da un oggetto.

(Ereditato da MethodInfo)
ICustomAttributeProvider.GetCustomAttributes(Boolean)

Restituisce una matrice di tutti gli attributi personalizzati definiti in questo membro, esclusi gli attributi denominati, oppure una matrice vuota se non sono presenti attributi personalizzati.

(Ereditato da MemberInfo)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

Restituisce una matrice di attributi personalizzati definiti in questo membro, identificati dal tipo o da una matrice vuota, se non sono presenti attributi personalizzati di quel tipo.

(Ereditato da MemberInfo)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Indica se per questo membro sono definite una o più istanze di attributeType.

(Ereditato da MemberInfo)

Metodi di estensione

GetCustomAttribute(MemberInfo, Type)

Recupera una attributo personalizzato di un tipo specificato che viene applicato a un membro specificato.

GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera un attributo personalizzato di un tipo specificato che viene applicato a un membro specificato e verifica facoltativamente i predecessori di tale membro.

GetCustomAttribute<T>(MemberInfo)

Recupera una attributo personalizzato di un tipo specificato che viene applicato a un membro specificato.

GetCustomAttribute<T>(MemberInfo, Boolean)

Recupera un attributo personalizzato di un tipo specificato che viene applicato a un membro specificato e verifica facoltativamente i predecessori di tale membro.

GetCustomAttributes(MemberInfo)

Recupera una raccolta di attributi personalizzati che vengono applicati a un membro specificato.

GetCustomAttributes(MemberInfo, Boolean)

Recupera una raccolta di attributi personalizzati che vengono applicati a un membro specificato e verifica facoltativamente i predecessori di tale membro.

GetCustomAttributes(MemberInfo, Type)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un membro specificato.

GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un membro specificato e verifica facoltativamente i predecessori di tale membro.

GetCustomAttributes<T>(MemberInfo)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un membro specificato.

GetCustomAttributes<T>(MemberInfo, Boolean)

Recupera una raccolta di attributi personalizzati di un tipo specificato che vengono applicati a un membro specificato e verifica facoltativamente i predecessori di tale membro.

IsDefined(MemberInfo, Type)

Indica se vengono applicati attributi personalizzati del tipo specificato a un membro specificato.

IsDefined(MemberInfo, Type, Boolean)

Indica se gli attributi personalizzati di un tipo specificato vengono applicati a un membro specificato e, facoltativamente, ai relativi predecessori.

GetMetadataToken(MemberInfo)

Ottiene un token di metadati per il membro specificato, se disponibile.

HasMetadataToken(MemberInfo)

Restituisce un valore che indica se un token di metadati è disponibile per il membro specificato.

GetBaseDefinition(MethodInfo)

Definisce e rappresenta un metodo dinamico che può essere compilato, eseguito e annullato. I metodi annullati possono essere sottoposti a Garbage Collection.

GetRuntimeBaseDefinition(MethodInfo)

Recupera un oggetto che rappresenta il metodo specificato nella classe di base diretta o indiretta in cui il metodo è stato inizialmente dichiarato.

Si applica a

Vedi anche