DynamicMethod.CreateDelegate 메서드

정의

동적 메서드를 완료하고 실행하는 데 사용할 수 있는 대리자를 만듭니다.

오버로드

Name Description
CreateDelegate(Type)

동적 메서드를 완료하고 실행하는 데 사용할 수 있는 대리자를 만듭니다.

CreateDelegate(Type, Object)

동적 메서드를 완료하고 대리자를 실행하는 데 사용할 수 있는 대리자를 만들고 대리자가 바인딩된 대리자 형식과 개체를 지정합니다.

CreateDelegate(Type)

동적 메서드를 완료하고 실행하는 데 사용할 수 있는 대리자를 만듭니다.

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

매개 변수

delegateType
Type

시그니처가 동적 메서드의 서명과 일치하는 대리자 형식입니다.

반품

동적 메서드를 실행하는 데 사용할 수 있는 지정된 형식의 대리자입니다.

특성

예외

동적 메서드에는 메서드 본문이 없습니다.

delegateType 에는 잘못된 수의 매개 변수 또는 잘못된 매개 변수 형식이 있습니다.

예제

다음 코드 예제에서는 두 개의 매개 변수를 사용하는 동적 메서드를 만듭니다. 이 예제에서는 첫 번째 매개 변수를 콘솔에 출력하는 간단한 함수 본문을 내보내고 두 번째 매개 변수를 메서드의 반환 값으로 사용합니다. 이 예제는 대리자를 생성하여 메서드를 완성한 후, 다른 매개변수로 대리자를 호출하고, 마지막으로 Invoke 메서드를 사용하여 동적 메서드를 호출합니다.

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
'

설명

CreateDelegate 메서드 또는 메서드를 호출하면 Invoke 동적 메서드가 완료됩니다. 매개 변수 정의를 수정하거나 MSIL(Microsoft 중간 언어)을 더 내보내는 등 동적 메서드를 변경하려는 추가 시도는 무시됩니다. 예외가 throw되지 않습니다.

고유한 MSIL 생성기가 있는 경우 동적 메서드에 대한 메서드 본문을 만들려면 메서드를 GetDynamicILInfo 호출하여 개체를 DynamicILInfo 가져옵니다. 고유한 MSIL 생성기가 없는 경우 메서드를 호출 GetILGenerator 하여 메서드 본문을 생성하는 데 사용할 수 있는 개체를 가져옵니다 ILGenerator .

추가 정보

적용 대상

CreateDelegate(Type, Object)

동적 메서드를 완료하고 대리자를 실행하는 데 사용할 수 있는 대리자를 만들고 대리자가 바인딩된 대리자 형식과 개체를 지정합니다.

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

매개 변수

delegateType
Type

시그니처가 동적 메서드의 서명과 일치하는 대리자 형식이며 첫 번째 매개 변수를 뺀 값입니다.

target
Object

대리자가 바인딩된 개체입니다. 동적 메서드의 첫 번째 매개 변수와 동일한 형식이어야 합니다.

반품

지정된 대상 개체를 사용하여 동적 메서드를 실행하는 데 사용할 수 있는 지정된 형식의 대리자입니다.

특성

예외

동적 메서드에는 메서드 본문이 없습니다.

target 가 동적 메서드의 첫 번째 매개 변수와 같은 형식이 아니고 해당 형식에 할당할 수 없습니다.

-또는-

delegateType 에는 잘못된 수의 매개 변수 또는 잘못된 매개 변수 형식이 있습니다.

예제

다음 코드 예제에서는 메서드가 호출될 때마다 동일한 인스턴스에서 작동하도록 형식의 인스턴스에 바인딩 DynamicMethod 하는 대리자를 만듭니다.

이 코드 예제는 프라이빗 필드를 가진 클래스 Example 을 정의하고, 첫 번째 클래스에서 파생된 클래스 DerivedFromExample, UseLikeStatic를 반환하고 Int32, Example 타입의 매개 변수를 갖는 형식의 대리자 Int32, UseLikeInstance를 반환하고 Int32 타입의 매개 변수를 갖는 형식의 대리자 Int32를 정의합니다.

그런 다음 예제 코드는 인스턴스 DynamicMethod 의 프라이빗 필드를 변경하고 이전 값을 반환하는 형식을 만듭니다Example.

메모

일반적으로 클래스의 내부 필드를 변경하는 것은 개체 지향 코딩 연습에 적합하지 않습니다.

예제 코드는 인스턴스 Example 를 만든 다음 두 대리자를 만듭니다. 첫 번째는 동적 메서드와 동일한 매개 변수를 포함하는 형식 UseLikeStatic입니다. 두 번째는 첫 번째 매개 변수(형식 UseLikeInstance)가 없는 형식 Example입니다. 이 대리자는 메서드 오버로드를 사용하여 CreateDelegate(Type, Object) 만들어집니다. 해당 메서드 오버로드의 두 번째 매개 변수는 인스턴스입니다 Example. 이 경우 방금 만든 인스턴스는 새로 만든 대리자에게 바인딩됩니다. 해당 대리자를 호출할 때마다 동적 메서드는 바인딩된 인스턴스 Example에서 작동합니다.

메모

이것은 .NET Framework 2.0에 도입된 대리자 바인딩의 완화된 규칙의 예이며, Delegate.CreateDelegate 메서드의 새로운 오버로드와 함께 제공됩니다. 자세한 내용은 Delegate 클래스를 참조하세요.

UseLikeStatic 대리자가 호출되어 해당 인스턴스 Example 가 대리자에게 UseLikeInstance 바인딩됩니다. UseLikeInstance 그런 다음 두 대리자가 동일한 인스턴스Example에서 작동할 수 있도록 대리자가 호출됩니다. 내부 필드 값의 변경 내용은 각 호출 후에 표시됩니다. 마지막으로 대리자는 UseLikeInstance 인스턴스 DerivedFromExample에 바인딩되고 대리자 호출은 반복됩니다.

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'

설명

이 메서드 오버로드는 특정 개체에 바인딩된 대리자를 만듭니다. 이러한 대리자는 첫 번째 인수를 통해 닫혀 있다고합니다. 메서드는 정적이지만 인스턴스 메서드인 것처럼 작동합니다. 인스턴스가 .입니다 target.

이 메서드 오버로드는 target 동적 메서드의 첫 번째 매개 변수와 동일한 형식이거나 해당 형식(예: 파생 클래스)에 할당할 수 있어야 합니다. 시그니처 delegateType 에는 첫 번째를 제외한 동적 메서드의 모든 매개 변수가 있습니다. 예를 들어 동적 메서드에 매개 변수가 String있고 Int32Byte , 매개 변수 delegateTypeInt32 가 있고 Byte; target 형식String인 경우입니다.

CreateDelegate 메서드 또는 메서드를 호출하면 Invoke 동적 메서드가 완료됩니다. 매개 변수 정의를 수정하거나 MSIL(Microsoft 중간 언어)을 더 내보내는 등 동적 메서드를 변경하려는 추가 시도는 무시됩니다. 예외가 throw되지 않습니다.

고유한 MSIL 생성기가 있는 경우 동적 메서드에 대한 메서드 본문을 만들려면 메서드를 GetDynamicILInfo 호출하여 개체를 DynamicILInfo 가져옵니다. 고유한 MSIL 생성기가 없는 경우 메서드를 호출 GetILGenerator 하여 메서드 본문을 생성하는 데 사용할 수 있는 개체를 가져옵니다 ILGenerator .

적용 대상