DynamicMethod.CreateDelegate Methode

Definition

Schließt die dynamische Methode ab und erstellt einen Delegaten, der zum Ausführen verwendet werden kann.

Überlädt

Name Beschreibung
CreateDelegate(Type)

Schließt die dynamische Methode ab und erstellt einen Delegaten, der zum Ausführen verwendet werden kann.

CreateDelegate(Type, Object)

Schließt die dynamische Methode ab und erstellt einen Delegaten, der zum Ausführen verwendet werden kann, wobei der Delegattyp und ein Objekt angegeben werden, an das der Delegate gebunden ist.

CreateDelegate(Type)

Schließt die dynamische Methode ab und erstellt einen Delegaten, der zum Ausführen verwendet werden kann.

public:
 Delegate ^ CreateDelegate(Type ^ delegateType);
public:
 override Delegate ^ CreateDelegate(Type ^ delegateType);
[System.Runtime.InteropServices.ComVisible(true)]
public Delegate CreateDelegate(Type delegateType);
[System.Runtime.InteropServices.ComVisible(true)]
public override sealed Delegate CreateDelegate(Type delegateType);
public override sealed Delegate CreateDelegate(Type delegateType);
[<System.Runtime.InteropServices.ComVisible(true)>]
member this.CreateDelegate : Type -> Delegate
[<System.Runtime.InteropServices.ComVisible(true)>]
override this.CreateDelegate : Type -> Delegate
override this.CreateDelegate : Type -> Delegate
Public Function CreateDelegate (delegateType As Type) As Delegate
Public Overrides NotOverridable Function CreateDelegate (delegateType As Type) As Delegate

Parameter

delegateType
Type

Ein Delegattyp, dessen Signatur mit der der dynamischen Methode übereinstimmt.

Gibt zurück

Ein Delegat des angegebenen Typs, der zum Ausführen der dynamischen Methode verwendet werden kann.

Attribute

Ausnahmen

Die dynamische Methode weist keinen Methodentext auf.

delegateType hat die falsche Anzahl von Parametern oder die falschen Parametertypen.

Beispiele

Im folgenden Codebeispiel wird eine dynamische Methode erstellt, die zwei Parameter verwendet. Im Beispiel wird ein einfacher Funktionstext ausgegeben, der den ersten Parameter in der Konsole druckt, und im Beispiel wird der zweite Parameter als Rückgabewert der Methode verwendet. Im Beispiel wird die Methode abgeschlossen, indem sie einen Delegaten erstellt, den Delegaten mit verschiedenen Parametern aufruft und schließlich die dynamische Methode mithilfe der Invoke Methode aufruft.

using System;
using System.Reflection;
using System.Reflection.Emit;
using Microsoft.VisualBasic;

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

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

        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello",
            typeof(int),
            helloArgs,
            typeof(Test).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.
        ILGenerator il = hello.GetILGenerator();
        // 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);

        // Create a delegate that represents the dynamic method. This
        // action completes the method, and any further attempts to
        // change the method will cause an exception.
        HelloInvoker hi =
            (HelloInvoker) hello.CreateDelegate(typeof(HelloInvoker));

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Executing delegate hi(\"Hello, World!\", 42) returned {0}",
            retval);

        // Do it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Executing delegate hi(\"Hi, Mom!\", 5280) returned {0}",
            retval);

        // 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 ValueType arguments
        // must be boxed.
        object objRet = hello.Invoke(null, invokeArgs);
        Console.WriteLine("hello.Invoke returned {0}", objRet);
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

Public Class Test
    ' Declare a delegate that will be used to execute the completed
    ' dynamic method. 
    Private Delegate Function HelloInvoker(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 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 Test class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(Test).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.
        Dim il As ILGenerator = hello.GetILGenerator()
        ' 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)

        ' Create a delegate that represents the dynamic method. This
        ' action completes the method, and any further attempts to
        ' change the method will cause an exception.
    Dim hi As HelloInvoker = _
            hello.CreateDelegate(GetType(HelloInvoker))

        ' Use the delegate to execute the dynamic method. Save and
        ' print the return value.
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Executing delegate hi(""Hello, World!"", 42) returned " _
            & retval)

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

        ' 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 ValueType arguments
        ' must be boxed. Note that this overload of Invoke is 
        ' inherited from MethodBase, and simply calls the more 
        ' complete overload of Invoke.
        Dim objRet As Object = hello.Invoke(Nothing, invokeArgs)
        Console.WriteLine("hello.Invoke returned " & objRet)
    End Sub
End Class

' This code example produces the following output:
'
'Hello, World!
'Executing delegate hi("Hello, World!", 42) returned 42
'
'Hi, Mom!
'Executing delegate hi("Hi, Mom!", 5280) returned 5280
'
'Hello, World!
'hello.Invoke returned 42
'

Hinweise

Durch Aufrufen der CreateDelegate Methode oder der Invoke Methode wird die dynamische Methode abgeschlossen. Alle weiteren Versuche, die dynamische Methode zu ändern, z. B. das Ändern von Parameterdefinitionen oder das Aussenden weiterer Microsoft-Zwischensprache (MSIL), wird ignoriert; es wird keine Ausnahme ausgelöst.

Um einen Methodentext für eine dynamische Methode zu erstellen, wenn Sie über einen eigenen MSIL-Generator verfügen, rufen Sie die GetDynamicILInfo Methode auf, um ein DynamicILInfo Objekt abzurufen. Wenn Sie nicht über ihren eigenen MSIL-Generator verfügen, rufen Sie die GetILGenerator Methode auf, um ein ILGenerator Objekt abzurufen, das zum Generieren des Methodentexts verwendet werden kann.

Weitere Informationen

Gilt für:

CreateDelegate(Type, Object)

Schließt die dynamische Methode ab und erstellt einen Delegaten, der zum Ausführen verwendet werden kann, wobei der Delegattyp und ein Objekt angegeben werden, an das der Delegate gebunden ist.

public:
 Delegate ^ CreateDelegate(Type ^ delegateType, System::Object ^ target);
public:
 override Delegate ^ CreateDelegate(Type ^ delegateType, System::Object ^ target);
[System.Runtime.InteropServices.ComVisible(true)]
public Delegate CreateDelegate(Type delegateType, object target);
[System.Runtime.InteropServices.ComVisible(true)]
public override sealed Delegate CreateDelegate(Type delegateType, object target);
public override sealed Delegate CreateDelegate(Type delegateType, object target);
[<System.Runtime.InteropServices.ComVisible(true)>]
member this.CreateDelegate : Type * obj -> Delegate
[<System.Runtime.InteropServices.ComVisible(true)>]
override this.CreateDelegate : Type * obj -> Delegate
override this.CreateDelegate : Type * obj -> Delegate
Public Function CreateDelegate (delegateType As Type, target As Object) As Delegate
Public Overrides NotOverridable Function CreateDelegate (delegateType As Type, target As Object) As Delegate

Parameter

delegateType
Type

Ein Delegattyp, dessen Signatur mit der der dynamischen Methode abzüglich des ersten Parameters übereinstimmt.

target
Object

Ein Objekt, an das der Delegat gebunden ist. Muss vom gleichen Typ wie der erste Parameter der dynamischen Methode sein.

Gibt zurück

Ein Delegat des angegebenen Typs, der zum Ausführen der dynamischen Methode mit dem angegebenen Zielobjekt verwendet werden kann.

Attribute

Ausnahmen

Die dynamische Methode weist keinen Methodentext auf.

target ist nicht derselbe Typ wie der erste Parameter der dynamischen Methode und kann diesem Typ nicht zugewiesen werden.

-oder-

delegateType hat die falsche Anzahl von Parametern oder die falschen Parametertypen.

Beispiele

Im folgenden Codebeispiel wird ein Delegat erstellt, der eine DynamicMethod Bindung an eine Instanz eines Typs angibt, sodass die Methode bei jedem Aufruf auf dieselbe Instanz wirkt.

Das Codebeispiel definiert eine Klasse Example mit einem privaten Feld, einer Klasse mit dem Namen DerivedFromExample , die von der ersten Klasse abgeleitet wird, einen Delegattyp, UseLikeStatic der zurückgegeben Int32 wird und Parameter vom Typ Example hat, und Int32einen Delegattyp mit dem Namen UseLikeInstance , der zurückgegeben Int32 wird und einen Parameter vom Typ Int32hat.

Der Beispielcode erstellt dann ein DynamicMethod-Objekt, das das private Feld einer Instanz von Example ändert und den vorherigen Wert zurückgibt.

Note

Im Allgemeinen ist das Ändern der internen Klassenfelder keine gute objektorientierte Codierungspraxis.

Der Beispielcode erstellt eine Instanz von Example und erstellt dann zwei Stellvertretungen. Der erste ist vom Typ UseLikeStatic, der die gleichen Parameter wie die dynamische Methode hat. Die zweite ist vom Typ UseLikeInstance, der den ersten Parameter (vom Typ Example) fehlt. Dieser Delegat wird mithilfe der CreateDelegate(Type, Object) Methodenüberladung erstellt. Der zweite Parameter dieser Methodenüberladung ist eine Instanz von Example, in diesem Fall die soeben erstellte Instanz, die an den neu erstellten Delegaten gebunden ist. Wenn diese Stellvertretung aufgerufen wird, wirkt die dynamische Methode auf die gebundene Instanz von Example.

Note

Dies ist ein Beispiel für die lockeren Regeln für die in .NET Framework 2.0 eingeführte Stellvertretungsbindung sowie neue Überladungen der Delegate.CreateDelegate Methode. Weitere Informationen finden Sie in der Delegate Klasse.

Der UseLikeStatic Delegat wird aufgerufen und übergibt die Instanz, die Example an den UseLikeInstance Delegaten gebunden ist. Anschließend wird der UseLikeInstance-Delegate aufgerufen, sodass beide Delegates auf dieselbe Instanz von Example wirken. Die Änderungen an den Werten des internen Felds werden nach jedem Aufruf angezeigt. Schließlich wird ein UseLikeInstance Delegat an eine Instanz von DerivedFromExample gebunden, und die Delegataufrufe werden wiederholt.

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

// These classes are for demonstration purposes.
//
public class Example
{
    private int id = 0;
    public Example(int id)
    {
        this.id = id;
    }
    public int ID { get { return id; }}
}

public class DerivedFromExample : Example
{
    public DerivedFromExample(int id) : base(id) {}
}

// Two delegates are declared: UseLikeInstance treats the dynamic
// method as if it were an instance method, and UseLikeStatic
// treats the dynamic method in the ordinary fashion.
//
public delegate int UseLikeInstance(int newID);
public delegate int UseLikeStatic(Example ex, int newID);

public class Demo
{
    public static void Main()
    {
        // This dynamic method changes the private id field. It has
        // no name; it returns the old id value (return type int);
        // it takes two parameters, an instance of Example and
        // an int that is the new value of id; and it is declared
        // with Example as the owner type, so it can access all
        // members, public and private.
        //
        DynamicMethod changeID = new DynamicMethod(
            "",
            typeof(int),
            new Type[] { typeof(Example), typeof(int) },
            typeof(Example)
        );

        // Get a FieldInfo for the private field 'id'.
        FieldInfo fid = typeof(Example).GetField(
            "id",
            BindingFlags.NonPublic | BindingFlags.Instance
        );

        ILGenerator ilg = changeID.GetILGenerator();

        // Push the current value of the id field onto the
        // evaluation stack. It's an instance field, so load the
        // instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldfld, fid);

        // Load the instance of Example again, load the new value
        // of id, and store the new field value.
        ilg.Emit(OpCodes.Ldarg_0);
        ilg.Emit(OpCodes.Ldarg_1);
        ilg.Emit(OpCodes.Stfld, fid);

        // The original value of the id field is now the only
        // thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret);

        // Create a delegate that uses changeID in the ordinary
        // way, as a static method that takes an instance of
        // Example and an int.
        //
        UseLikeStatic uls =
            (UseLikeStatic) changeID.CreateDelegate(
                typeof(UseLikeStatic)
            );

        // Create an instance of Example with an id of 42.
        //
        Example ex = new Example(42);

        // Create a delegate that is bound to the instance of
        // of Example. This is possible because the first
        // parameter of changeID is of type Example. The
        // delegate has all the parameters of changeID except
        // the first.
        UseLikeInstance uli =
            (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                ex
            );

        // First, change the value of id by calling changeID as
        // a static method, passing in the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(ex, 1492)
        );

        // Change the value of id again using the delegate bound
        // to the instance of Example.
        //
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(2700)
        );

        Console.WriteLine("Final value of id: {0}", ex.ID);

        // Now repeat the process with a class that derives
        // from Example.
        //
        DerivedFromExample dfex = new DerivedFromExample(71);

        uli = (UseLikeInstance) changeID.CreateDelegate(
                typeof(UseLikeInstance),
                dfex
            );

        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uls(dfex, 73)
        );
        Console.WriteLine(
            "Change the value of id; previous value: {0}",
            uli(79)
        );
        Console.WriteLine("Final value of id: {0}", dfex.ID);
    }
}

/* This code example produces the following output:

Change the value of id; previous value: 42
Change the value of id; previous value: 1492
Final value of id: 2700
Change the value of id; previous value: 71
Change the value of id; previous value: 73
Final value of id: 79
 */
Imports System.Reflection
Imports System.Reflection.Emit

' These classes are for demonstration purposes.
'
Public Class Example
    Private _id As Integer = 0
    
    Public Sub New(ByVal newId As Integer) 
        _id = newId    
    End Sub
    
    Public ReadOnly Property ID() As Integer 
        Get
            Return _id
        End Get
    End Property 
End Class

Public Class DerivedFromExample
    Inherits Example
    
    Public Sub New(ByVal newId As Integer) 
        MyBase.New(newId)
    End Sub
End Class
 
' Two delegates are declared: UseLikeInstance treats the dynamic
' method as if it were an instance method, and UseLikeStatic
' treats the dynamic method in the ordinary fashion.
' 
Public Delegate Function UseLikeInstance(ByVal newID As Integer) _
    As Integer 
Public Delegate Function UseLikeStatic(ByVal ex As Example, _
    ByVal newID As Integer) As Integer 

Public Class Demo
    
    Public Shared Sub Main() 
        ' This dynamic method changes the private _id field. It 
        ' has no name; it returns the old _id value (return type 
        ' Integer); it takes two parameters, an instance of Example 
        ' and an Integer that is the new value of _id; and it is 
        ' declared with Example as the owner type, so it can 
        ' access all members, public and private.
        '
        Dim changeID As New DynamicMethod( _
            "", _
            GetType(Integer), _
            New Type() {GetType(Example), GetType(Integer)}, _
            GetType(Example) _
        )
        
        ' Get a FieldInfo for the private field '_id'.
        Dim fid As FieldInfo = GetType(Example).GetField( _
            "_id", _
            BindingFlags.NonPublic Or BindingFlags.Instance _
        )
        
        Dim ilg As ILGenerator = changeID.GetILGenerator()
        
        ' Push the current value of the id field onto the 
        ' evaluation stack. It's an instance field, so load the
        ' instance of Example before accessing the field.
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldfld, fid)
        
        ' Load the instance of Example again, load the new value 
        ' of id, and store the new field value. 
        ilg.Emit(OpCodes.Ldarg_0)
        ilg.Emit(OpCodes.Ldarg_1)
        ilg.Emit(OpCodes.Stfld, fid)
        
        ' The original value of the id field is now the only 
        ' thing on the stack, so return from the call.
        ilg.Emit(OpCodes.Ret)
        
        
        ' Create a delegate that uses changeID in the ordinary
        ' way, as a static method that takes an instance of
        ' Example and an Integer.
        '
        Dim uls As UseLikeStatic = CType( _
            changeID.CreateDelegate(GetType(UseLikeStatic)), _
            UseLikeStatic _
        )
        
        ' Create an instance of Example with an id of 42.
        '
        Dim ex As New Example(42)
        
        ' Create a delegate that is bound to the instance of 
        ' of Example. This is possible because the first 
        ' parameter of changeID is of type Example. The 
        ' delegate has all the parameters of changeID except
        ' the first.
        Dim uli As UseLikeInstance = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                ex), _
            UseLikeInstance _
        )
        
        ' First, change the value of _id by calling changeID as
        ' a static method, passing in the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(ex, 1492) _
        )
        
        ' Change the value of _id again using the delegate 
        ' bound to the instance of Example.
        '
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(2700) _
        )
        
        Console.WriteLine("Final value of _id: {0}", ex.ID)
    

        ' Now repeat the process with a class that derives
        ' from Example.
        '
        Dim dfex As New DerivedFromExample(71)

        uli = CType( _
            changeID.CreateDelegate( _
                GetType(UseLikeInstance), _
                dfex), _
            UseLikeInstance _
        )

        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uls(dfex, 73) _
        )
        Console.WriteLine( _
            "Change the value of _id; previous value: {0}", _
            uli(79) _
        )
        Console.WriteLine("Final value of _id: {0}", dfex.ID)

    End Sub
End Class

' This code example produces the following output:
'
'Change the value of _id; previous value: 42
'Change the value of _id; previous value: 1492
'Final value of _id: 2700
'Change the value of _id; previous value: 71
'Change the value of _id; previous value: 73
'Final value of _id: 79'

Hinweise

Diese Methodenüberladung erstellt einen Delegaten, der an ein bestimmtes Objekt gebunden ist. Ein solcher Delegat wird als über sein erstes Argument geschlossen bezeichnet. Obwohl die Methode statisch ist, fungiert sie so, als wäre sie eine Instanzmethode; die Instanz ist target.

Diese Methodenüberladung muss target denselben Typ wie der erste Parameter der dynamischen Methode aufweisen oder diesem Typ zugewiesen werden können (z. B. eine abgeleitete Klasse). Die Signatur von delegateType enthält alle Parameter der dynamischen Methode, mit Ausnahme des ersten. Wenn die dynamische Methode z. B. die Parameter String, Int32 und Byte hat, dann hat delegateType die Parameter Int32 und Byte; target ist vom Typ String.

Durch Aufrufen der CreateDelegate Methode oder der Invoke Methode wird die dynamische Methode abgeschlossen. Alle weiteren Versuche, die dynamische Methode zu ändern, z. B. das Ändern von Parameterdefinitionen oder das Aussenden weiterer Microsoft-Zwischensprache (MSIL), wird ignoriert; es wird keine Ausnahme ausgelöst.

Um einen Methodentext für eine dynamische Methode zu erstellen, wenn Sie über einen eigenen MSIL-Generator verfügen, rufen Sie die GetDynamicILInfo Methode auf, um ein DynamicILInfo Objekt abzurufen. Wenn Sie nicht über ihren eigenen MSIL-Generator verfügen, rufen Sie die GetILGenerator Methode auf, um ein ILGenerator Objekt abzurufen, das zum Generieren des Methodentexts verwendet werden kann.

Gilt für: