DynamicMethod.CreateDelegate DynamicMethod.CreateDelegate DynamicMethod.CreateDelegate DynamicMethod.CreateDelegate Method

定義

動的メソッドを完了し、それを実行するために使用できるデリゲートを作成します。Completes the dynamic method and creates a delegate that can be used to execute it.

オーバーロード

CreateDelegate(Type) CreateDelegate(Type) CreateDelegate(Type) CreateDelegate(Type)

動的メソッドを完了し、それを実行するために使用できるデリゲートを作成します。Completes the dynamic method and creates a delegate that can be used to execute it.

CreateDelegate(Type, Object) CreateDelegate(Type, Object) CreateDelegate(Type, Object) CreateDelegate(Type, Object)

デリゲート型とデリゲートのバインド先となるオブジェクトを指定して、動的メソッドを完了し、メソッドの実行に使用できるデリゲートを作成します。Completes the dynamic method and creates a delegate that can be used to execute it, specifying the delegate type and an object the delegate is bound to.

CreateDelegate(Type) CreateDelegate(Type) CreateDelegate(Type) CreateDelegate(Type)

動的メソッドを完了し、それを実行するために使用できるデリゲートを作成します。Completes the dynamic method and creates a delegate that can be used to execute it.

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

パラメーター

delegateType
Type Type Type Type

シグネチャが動的メソッドのシグネチャと一致するデリゲート型。A delegate type whose signature matches that of the dynamic method.

戻り値

動的メソッドの実行に使用できる指定した型のデリゲート。A delegate of the specified type, which can be used to execute the dynamic method.

例外

動的メソッドにメソッド本体がありません。The dynamic method has no method body.

delegateType のパラメーターの数に誤りがあるか、パラメーターの型に誤りがあります。delegateType has the wrong number of parameters or the wrong parameter types.

次のコード例では、2 つのパラメーターを受け取る動的メソッドを作成します。The following code example creates a dynamic method that takes two parameters. 例では、最初のパラメーターをコンソールに出力する単純な関数の本体を出力して、例では、2 番目のパラメーターを使用して、メソッドの戻り値として。The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. 例では、デリゲートを作成して、メソッドが完了すると、別のパラメーターを持つデリゲートを呼び出すおよび動的メソッドを使用して、最後に呼び出す、Invokeメソッド。The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the Invoke method.

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

public ref class Test
{   
};

// Declare a delegate that will be used to execute the completed
// dynamic method.
delegate int HelloInvoker(String^ msg, int ret);

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

    // 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 = gcnew DynamicMethod("Hello", 
        int::typeid,
        helloArgs,
        Test::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.
    ILGenerator^ ilgen = hello->GetILGenerator();
    // Load the first argument, which is a string, onto the stack.
    ilgen->Emit(OpCodes::Ldarg_0);
    // Call the overload of Console.WriteLine that prints a string.
    ilgen->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.
    ilgen->Emit(OpCodes::Ldarg_1);
    ilgen->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^ helloDelegate =
        (HelloInvoker^) hello->CreateDelegate(HelloInvoker::typeid);

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

    // Do it again, with different arguments.
    returnValue = helloDelegate("\r\nHi, Mom!", 5280);
    Console::WriteLine("helloDelegate(\"Hi, Mom!\", 5280) returned {0}",
        returnValue);

    // Create an array of arguments to use with the Invoke method.
    array<Object^>^ delegateArgs = {"\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^ returnValueObject = hello->Invoke(nullptr, delegateArgs);
    Console::WriteLine("hello.Invoke returned {0}", returnValueObject);
}
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
Imports System.Reflection
Imports System.Reflection.Emit
Imports Microsoft.VisualBasic

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
'

注釈

呼び出す、CreateDelegateメソッドまたはInvokeメソッドは、動的メソッドを完了します。Calling the CreateDelegate method or the Invoke method completes the dynamic method. さらにパラメーターの定義の変更など、動的メソッドを変更しようとしています。 または以上の Microsoft 中間言語 (MSIL) の出力は無視されます。例外はスローされません。Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown.

MSIL ジェネレーターがある場合は、動的メソッドのメソッド本体を作成するには、呼び出し、GetDynamicILInfoメソッドを取得する、DynamicILInfoオブジェクト。To create a method body for a dynamic method when you have your own MSIL generator, call the GetDynamicILInfo method to obtain a DynamicILInfo object. MSIL ジェネレーターがいない場合は、呼び出し、GetILGeneratorメソッドを取得する、ILGeneratorメソッド本体を生成するために使用できるオブジェクト。If you do not have your own MSIL generator, call the GetILGenerator method to obtain an ILGenerator object that can be used to generate the method body.

こちらもご覧ください

CreateDelegate(Type, Object) CreateDelegate(Type, Object) CreateDelegate(Type, Object) CreateDelegate(Type, Object)

デリゲート型とデリゲートのバインド先となるオブジェクトを指定して、動的メソッドを完了し、メソッドの実行に使用できるデリゲートを作成します。Completes the dynamic method and creates a delegate that can be used to execute it, specifying the delegate type and an object the delegate is bound to.

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

パラメーター

delegateType
Type Type Type Type

1 つ目のパラメーターがない、シグネチャが動的メソッドのシグネチャと一致するデリゲート型。A delegate type whose signature matches that of the dynamic method, minus the first parameter.

target
Object Object Object Object

デリゲートのバインド先となるオブジェクト。An object the delegate is bound to. 動的メソッドの 1 つ目のパラメーターと同じ型であることが必要です。Must be of the same type as the first parameter of the dynamic method.

戻り値

指定した対象オブジェクトで動的メソッドの実行に使用できる、指定した型のデリゲート。A delegate of the specified type, which can be used to execute the dynamic method with the specified target object.

例外

動的メソッドにメソッド本体がありません。The dynamic method has no method body.

target が動的メソッドの 1 つ目のパラメーターと同じ型でないため、この型に割り当てることはできません。target is not the same type as the first parameter of the dynamic method, and is not assignable to that type.

または-or- delegateType のパラメーターの数に誤りがあるか、パラメーターの型に誤りがあります。delegateType has the wrong number of parameters or the wrong parameter types.

次のコード例は、バインドするデリゲートを作成、DynamicMethod型のインスタンス、メソッドでは、毎回を同じインスタンス上に機能するため、これが呼び出されます。The following code example creates delegate that binds a DynamicMethod to an instance of a type, so that the method acts on the same instance each time it is invoked.

コード例は、という名前のクラスを定義しますExample、クラスの名前、プライベート フィールドを持つDerivedFromExample最初のクラスから派生したという名前のデリゲート型UseLikeStaticを返すInt32型のパラメーターを持ち、ExampleInt32。、という名前のデリゲート型とUseLikeInstanceを返すInt32型の 1 つのパラメーターとInt32します。The code example defines a class named Example with a private field, a class named DerivedFromExample that derives from the first class, a delegate type named UseLikeStatic that returns Int32 and has parameters of type Example and Int32, and a delegate type named UseLikeInstance that returns Int32 and has one parameter of type Int32.

コード例を作成し、DynamicMethodのインスタンスのプライベート フィールドが変更されたExample前の値を返します。The example code then creates a DynamicMethod that changes the private field of an instance of Example and returns the previous value.

注意

一般に、クラスの内部フィールドを変更するは適切なオブジェクト指向のコーディングの推奨手順です。In general, changing the internal fields of classes is not good object-oriented coding practice.

コード例は、のインスタンスを作成します。Exampleし、2 つのデリゲートを作成します。The example code creates an instance of Example and then creates two delegates. 型の 1 つは、 UseLikeStatic、動的メソッドと同じパラメーターを持ちます。The first is of type UseLikeStatic, which has the same parameters as the dynamic method. 型の 2 つ目は、 UseLikeInstance、最初のパラメーターを持たない (型のExample)。The second is of type UseLikeInstance, which lacks the first parameter (of type Example). 使用してこのデリゲートを作成、CreateDelegate(Type, Object)メソッドのオーバー ロードは、2 つ目メソッド オーバー ロードのパラメーターのインスタンスであるExample、ここでは、新しく作成されたデリゲートにバインドされている、先ほど作成したインスタンス。This delegate is created using the CreateDelegate(Type, Object) method overload; the second parameter of that method overload is an instance of Example, in this case the instance just created, which is bound to the newly created delegate. 動的メソッドはのバインドされたインスタンスに対してそのデリゲートが呼び出されるたびにExampleします。Whenever that delegate is invoked, the dynamic method acts on the bound instance of Example.

注意

これで導入されたデリゲート バインディングの緩和された規則の例、.NET Framework 2.0.NET Framework 2.0の新しいオーバー ロードと共に、Delegate.CreateDelegateメソッド。This is an example of the relaxed rules for delegate binding introduced in the .NET Framework 2.0.NET Framework 2.0, along with new overloads of the Delegate.CreateDelegate method. 詳細については、Delegate クラスを参照してください。For more information, see the Delegate class.

UseLikeStaticデリゲートが呼び出されるのインスタンスに渡しますExampleにバインドされている、UseLikeInstanceを委任します。The UseLikeStatic delegate is invoked, passing in the instance of Example that is bound to the UseLikeInstance delegate. 次に、UseLikeInstanceデリゲートが呼び出される、両方のデリゲートがの同じインスタンスで機能するようExampleします。Then the UseLikeInstance delegate is invoked, so that both delegates act on the same instance of Example. 内部フィールドの値の変更は、各呼び出しの後に表示されます。The changes in the values of the internal field are displayed after each call. 最後に、UseLikeInstanceのインスタンスにデリゲートをバインドDerivedFromExampleデリゲートの呼び出しが繰り返されます。Finally, a UseLikeInstance delegate is bound to an instance of DerivedFromExample, and the delegate calls are repeated.

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
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' 

注釈

このメソッドのオーバー ロードは、特定のオブジェクトにバインドされたデリゲートを作成します。This method overload creates a delegate bound to a particular object. このようなデリゲートは、最初の引数を閉じると表現されます。Such a delegate is said to be closed over its first argument. インスタンス メソッドの場合と同様、メソッドは静的ですが、機能しますインスタンスがtargetします。Although the method is static, it acts as if it were an instance method; the instance is target.

このメソッドのオーバー ロードが必要ですtarget、動的メソッドの最初のパラメーターと同じ型か、またはその型 (たとえば、派生クラス) に割り当てられます。This method overload requires target to be of the same type as the first parameter of the dynamic method, or to be assignable to that type (for example, a derived class). シグネチャdelegateTypeに動的メソッドの先頭を除くのすべてのパラメーターがあります。The signature of delegateType has all the parameters of the dynamic method except the first. たとえば、動的メソッドにパラメーター StringInt32、およびByte、しdelegateTypeパラメーターを持つInt32Byte;targetの種類はStringします。For example, if the dynamic method has the parameters String, Int32, and Byte, then delegateType has the parameters Int32 and Byte; target is of type String.

呼び出す、CreateDelegateメソッドまたはInvokeメソッドは、動的メソッドを完了します。Calling the CreateDelegate method or the Invoke method completes the dynamic method. さらにパラメーターの定義の変更など、動的メソッドを変更しようとしています。 または以上の Microsoft 中間言語 (MSIL) の出力は無視されます。例外はスローされません。Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown.

MSIL ジェネレーターがある場合は、動的メソッドのメソッド本体を作成するには、呼び出し、GetDynamicILInfoメソッドを取得する、DynamicILInfoオブジェクト。To create a method body for a dynamic method when you have your own MSIL generator, call the GetDynamicILInfo method to obtain a DynamicILInfo object. MSIL ジェネレーターがいない場合は、呼び出し、GetILGeneratorメソッドを取得する、ILGeneratorメソッド本体を生成するために使用できるオブジェクト。If you do not have your own MSIL generator, call the GetILGenerator method to obtain an ILGenerator object that can be used to generate the method body.

適用対象