Szerkesztés

Megosztás a következőn keresztül:


DynamicMethod Constructors

Definition

Creates a dynamic method.

Overloads

DynamicMethod(String, Type, Type[])

Initializes an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.

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

Initializes an anonymously hosted dynamic method, specifying the method name, return type, parameter types, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

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

Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, and module.

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

Creates a dynamic method, specifying the method name, return type, parameter types, and the type with which the dynamic method is logically associated.

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

Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

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

Creates a dynamic method, specifying the method name, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

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

Creates a dynamic method that is global to a module, specifying the method name, attributes, calling convention, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

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

Creates a dynamic method, specifying the method name, attributes, calling convention, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

DynamicMethod(String, Type, Type[])

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Initializes an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type())

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

Exceptions

An element of parameterTypes is null or Void.

name is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Remarks

The dynamic method that is created by this constructor is associated with an anonymous assembly instead of an existing type or module. The anonymous assembly exists only to provide a sandbox environment for dynamic methods, that is, to isolate them from other code. This environment makes it safe for the dynamic method to be emitted and executed by partially trusted code.

This constructor specifies that just-in-time (JIT) visibility checks will be enforced for the Microsoft intermediate language (MSIL) of the dynamic method. That is, the code in the dynamic method has access to public methods of public classes. Exceptions are thrown if the method tries to access types or members that are private, protected, or internal (Friend in Visual Basic). To create a dynamic method that has restricted ability to skip JIT visibility checks, use the DynamicMethod(String, Type, Type[], Boolean) constructor.

When an anonymously hosted dynamic method is constructed, the call stack of the emitting assembly is included. When the method is invoked, the permissions of the emitting assembly are used instead of the permissions of the actual caller. Thus, the dynamic method cannot execute at a higher level of privilege than that of the assembly that emitted it, even if it is passed to and executed by an assembly that has a higher trust level.

This constructor specifies the method attributes MethodAttributes.Public and MethodAttributes.Static, and the calling convention CallingConventions.Standard.

Note

This constructor was introduced in the .NET Framework 3.5 or later.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Initializes an anonymously hosted dynamic method, specifying the method name, return type, parameter types, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes, bool restrictedSkipVisibility);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes, bool restrictedSkipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), restrictedSkipVisibility As Boolean)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

restrictedSkipVisibility
Boolean

true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method, with this restriction: the trust level of the assemblies that contain those types and members must be equal to or less than the trust level of the call stack that emits the dynamic method; otherwise, false.

Exceptions

An element of parameterTypes is null or Void.

name is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Remarks

The dynamic method that is created by this constructor is associated with an anonymous assembly instead of an existing type or module. The anonymous assembly exists only to provide a sandbox environment for dynamic methods, that is, to isolate them from other code. This environment makes it safe for the dynamic method to be emitted and executed by partially trusted code.

Anonymously hosted dynamic methods do not have automatic access to any types or members that are private, protected, or internal (Friend in Visual Basic). This is different from dynamic methods that are associated with an existing type or module, which have access to hidden members in their associated scope.

Specify true for restrictedSkipVisibility if your dynamic method has to access types or members that are private, protected, or internal. This gives the dynamic method restricted access to these members. That is, the members can be accessed only if the following conditions are met:

  • The target members belong to an assembly that has a level of trust equal to or lower than the call stack that emits the dynamic method.

  • The call stack that emits the dynamic method is granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag. This is always true when the code is executed with full trust. For partially trusted code, it is true only if the host explicitly grants the permission.

    Important

    If the permission has not been granted, a security exception is thrown when CreateDelegate is called or when the dynamic method is invoked, not when this constructor is called. No special permissions are required to emit the dynamic method.

For example, a dynamic method that is created with restrictedSkipVisibility set to true can access a private member of any assembly on the call stack if the call stack has been granted restricted member access. If the dynamic method is created with partially trusted code on the call stack, it cannot access a private member of a type in a .NET Framework assembly, because such assemblies are fully trusted.

If restrictedSkipVisibility is false, JIT visibility checks are enforced. The code in the dynamic method has access to public methods of public classes, and exceptions are thrown if it tries to access types or members that are private, protected, or internal.

When an anonymously hosted dynamic method is constructed, the call stack of the emitting assembly is included. When the method is invoked, the permissions of the emitting call stack are used instead of the permissions of the actual caller. Thus, the dynamic method cannot execute at a higher level of privilege than that of the assembly that emitted it, even if it is passed to and executed by an assembly that has a higher trust level.

This constructor specifies the method attributes MethodAttributes.Public and MethodAttributes.Static, and the calling convention CallingConventions.Standard.

Note

This constructor was introduced in the .NET Framework 3.5 or later.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, and module.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module

A Module representing the module with which the dynamic method is to be logically associated.

Exceptions

An element of parameterTypes is null or Void.

-or-

m is a module that provides anonymous hosting for dynamic methods.

name is null.

-or-

m is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Examples

The following code example creates a dynamic method that takes two parameters. 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. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) 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.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
'

Remarks

This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, calling convention CallingConventions.Standard, and does not skip just-in-time (JIT) visibility checks.

The dynamic method created with this constructor has access to public and internal (Friend in Visual Basic) members of all the types contained in module m.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: m is a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method, specifying the method name, return type, parameter types, and the type with which the dynamic method is logically associated.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes, Type owner);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type

A Type with which the dynamic method is logically associated. The dynamic method has access to all members of the type.

Exceptions

An element of parameterTypes is null or Void.

-or-

owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

name is null.

-or-

owner is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Examples

The following code example creates a DynamicMethod that is logically associated with a type. This association gives it access to the private members of that type.

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.

The example code then creates a DynamicMethod that changes the private field of an instance of Example and returns the previous value.

Note

In general, changing the internal fields of classes is not good object-oriented coding practice.

The example code creates an instance of Example and then creates two delegates. The first is of type UseLikeStatic, which has the same parameters as the dynamic method. The second is of type UseLikeInstance, which lacks the first parameter (of type 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. Whenever that delegate is invoked, the dynamic method acts on the bound instance of Example.

Note

This is an example of the relaxed rules for delegate binding introduced in the .NET Framework 2.0, along with new overloads of the Delegate.CreateDelegate method. For more information, see the Delegate class.

The UseLikeStatic delegate is invoked, passing in the instance of Example that is bound to the UseLikeInstance delegate. 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. 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.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'

Remarks

The dynamic method created with this constructor has access to all members of the type owner, and to public and internal (Friend in Visual Basic) members of all the other types in the module that contains owner.

This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, calling convention CallingConventions.Standard, and does not skip just-in-time (JIT) visibility checks.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: owner is in a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method that is global to a module, specifying the method name, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m, bool skipVisibility);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module

A Module representing the module with which the dynamic method is to be logically associated.

skipVisibility
Boolean

true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method.

Exceptions

An element of parameterTypes is null or Void.

-or-

m is a module that provides anonymous hosting for dynamic methods.

name is null.

-or-

m is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Remarks

This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, and calling convention CallingConventions.Standard.

The dynamic method created with this constructor has access to public and internal (Friend in Visual Basic) members of all the types in contained module m. Skipping the JIT compiler's visibility checks allows the dynamic method to access private and protected members of all other types as well. This is useful, for example, when writing code to serialize objects.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: m is a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method, specifying the method name, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod (string name, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility);
public DynamicMethod (string name, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type

A Type with which the dynamic method is logically associated. The dynamic method has access to all members of the type.

skipVisibility
Boolean

true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

Exceptions

An element of parameterTypes is null or Void.

-or-

owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

name is null.

-or-

owner is null.

.NET Framework and .NET Core versions older than 2.1: returnType is a type for which IsByRef returns true.

Remarks

The dynamic method created with this constructor has access to all members of the type owner, and to public and internal (Friend in Visual Basic) members of all the other types in the module that contains owner. Skipping the JIT compiler's visibility checks allows the dynamic method to access private and protected members of all other types as well. This is useful, for example, when writing code to serialize objects.

This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, and calling convention CallingConventions.Standard.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: owner is in a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method that is global to a module, specifying the method name, attributes, calling convention, return type, parameter types, module, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

public:
 DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, System::Reflection::Module ^ m, bool skipVisibility);
public DynamicMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, System.Reflection.Module m, bool skipVisibility);
public DynamicMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, System.Reflection.Module m, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * System.Reflection.Module * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), m As Module, skipVisibility As Boolean)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

attributes
MethodAttributes

A bitwise combination of MethodAttributes values that specifies the attributes of the dynamic method. The only combination allowed is Public and Static.

callingConvention
CallingConventions

The calling convention for the dynamic method. Must be Standard.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module

A Module representing the module with which the dynamic method is to be logically associated.

skipVisibility
Boolean

true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

Exceptions

An element of parameterTypes is null or Void.

-or-

m is a module that provides anonymous hosting for dynamic methods.

name is null.

-or-

m is null.

attributes is a combination of flags other than Public and Static.

-or-

callingConvention is not Standard.

-or-

returnType is a type for which IsByRef returns true.

Remarks

The dynamic method created with this constructor has access to public and internal (Friend in Visual Basic) members of all the public and internal types contained in module m.

Skipping the JIT compiler's visibility checks allows the dynamic method to access private and protected members of all other types in the module and in all other assemblies as well. This is useful, for example, when writing code to serialize objects.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: m is a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to

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

Source:
DynamicMethod.cs
Source:
DynamicMethod.cs
Source:
DynamicMethod.cs

Creates a dynamic method, specifying the method name, attributes, calling convention, return type, parameter types, the type with which the dynamic method is logically associated, and whether just-in-time (JIT) visibility checks should be skipped for types and members accessed by the Microsoft intermediate language (MSIL) of the dynamic method.

public:
 DynamicMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes, Type ^ owner, bool skipVisibility);
public DynamicMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility);
public DynamicMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type owner, bool skipVisibility);
new System.Reflection.Emit.DynamicMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type * bool -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type(), owner As Type, skipVisibility As Boolean)

Parameters

name
String

The name of the dynamic method. This can be a zero-length string, but it cannot be null.

attributes
MethodAttributes

A bitwise combination of MethodAttributes values that specifies the attributes of the dynamic method. The only combination allowed is Public and Static.

callingConvention
CallingConventions

The calling convention for the dynamic method. Must be Standard.

returnType
Type

A Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

An array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type

A Type with which the dynamic method is logically associated. The dynamic method has access to all members of the type.

skipVisibility
Boolean

true to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

Exceptions

An element of parameterTypes is null or Void.

-or-

owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

name is null.

-or-

owner is null.

attributes is a combination of flags other than Public and Static.

-or-

callingConvention is not Standard.

-or-

returnType is a type for which IsByRef returns true.

Remarks

The dynamic method is global to the module that contains the type owner. It has access to all members of the type owner.

The dynamic method created with this constructor has access to all members of the type owner, and to public and internal (Friend in Visual Basic) members of all the types contained in the module that contains owner. Skipping the JIT compiler's visibility checks allows the dynamic method to access private and protected members of all other types as well. This is useful, for example, when writing code to serialize objects.

Note

For backward compatibility, this constructor demands SecurityPermission with the SecurityPermissionFlag.ControlEvidence flag if the following conditions are both true: owner is in a module other than the calling module, and the demand for ReflectionPermission with the ReflectionPermissionFlag.MemberAccess flag has failed. If the demand for SecurityPermission succeeds, the operation is allowed.

See also

Applies to