DynamicMethod DynamicMethod DynamicMethod DynamicMethod Constructors

定义

重载

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

初始化匿名承载的动态方法,指定方法名称、返回类型和参数类型。Initializes an anonymously hosted dynamic method, specifying the method name, return type, and parameter types.

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

初始化匿名托管的动态方法,同时指定方法名称、返回类型、参数类型并指定是否应针对动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员跳过实时 (JIT) 可见性检查。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) DynamicMethod(String, Type, Type[], Module) DynamicMethod(String, Type, Type[], Module) 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) DynamicMethod(String, Type, Type[], Type) DynamicMethod(String, Type, Type[], Type) 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) DynamicMethod(String, Type, Type[], Module, Boolean) DynamicMethod(String, Type, Type[], Module, Boolean) DynamicMethod(String, Type, Type[], Module, Boolean)

创建一个对模块全局有效的动态方法,指定方法名称、返回类型、参数类型和模块,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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) DynamicMethod(String, Type, Type[], Type, Boolean) DynamicMethod(String, Type, Type[], Type, Boolean) DynamicMethod(String, Type, Type[], Type, Boolean)

创建一个动态方法,指定方法名称、返回类型、参数类型、动态方法逻辑关联的类型,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Module, Boolean)

创建一个对模块全局有效的动态方法,指定方法名称、属性、调用约定、返回类型、参数类型和模块,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean) DynamicMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type, Boolean)

创建一个动态方法,指定方法名称、特性、调用约定、返回类型、参数类型、动态方法逻辑关联的类型,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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[]) DynamicMethod(String, Type, Type[]) DynamicMethod(String, Type, Type[]) DynamicMethod(String, Type, Type[])

初始化匿名承载的动态方法,指定方法名称、返回类型和参数类型。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);
new System.Reflection.Emit.DynamicMethod : string * Type * Type[] -> System.Reflection.Emit.DynamicMethod
Public Sub New (name As String, returnType As Type, parameterTypes As Type())

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

注解

此构造函数创建的动态方法是匿名的程序集,而不是一个现有类型或模块相关联。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.

此构造函数指定,在实时 (JIT) 可见性检查将强制实施为 Microsoft 中间语言 (MSIL) 的动态方法。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. 如果尝试访问的是类型或成员方法引发异常privateprotected,或internal(Friend在 Visual Basic 中)。Exceptions are thrown if the method tries to access types or members that are private, protected, or internal (Friend in Visual Basic). 若要创建具有受限能力跳过 JIT 可见性检查的动态方法,请使用DynamicMethod(String, Type, Type[], Boolean)构造函数。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.

此构造函数指定方法属性MethodAttributes.PublicMethodAttributes.Static,并调用约定CallingConventions.StandardThis constructor specifies the method attributes MethodAttributes.Public and MethodAttributes.Static, and the calling convention CallingConventions.Standard.

备注

此构造函数中引入了 .NET Framework 3.5.NET Framework 3.5或更高版本。This constructor was introduced in the .NET Framework 3.5.NET Framework 3.5 or later.

另请参阅

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

初始化匿名托管的动态方法,同时指定方法名称、返回类型、参数类型并指定是否应针对动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员跳过实时 (JIT) 可见性检查。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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

restrictedSkipVisibility
Boolean Boolean Boolean Boolean

如果为 true,则跳过针对动态方法的 MSIL 访问的类型和成员进行的 JIT 可见性检查,含此限制:包含这些类型和成员的程序集的信任级别必须等于或小于发出动态方法的调用堆栈的信任级别;否则为 falsetrue 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.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

注解

此构造函数创建的动态方法是匿名的程序集,而不是一个现有类型或模块相关联。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.

匿名托管动态方法不能为任何类型或成员的自动访问privateprotected,或internal(Friend在 Visual Basic 中)。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.

指定true有关restrictedSkipVisibility动态方法具有访问类型或成员privateprotected,或internalSpecify 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.

  • 发出动态方法的调用堆栈授予ReflectionPermissionReflectionPermissionFlag.RestrictedMemberAccess标志。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. 对于部分受信任的代码,它为 true,仅当主机显式授予的权限。For partially trusted code, it is true only if the host explicitly grants the permission.

    重要

    如果尚未授予该权限,安全异常时引发CreateDelegate调用或调用动态方法时,不在此构造函数调用。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.

例如,使用创建的动态方法restrictedSkipVisibility设置为true可以访问私有成员的调用堆栈上的任何程序集,调用堆栈是否已被授予了受限的成员访问权限。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. 如果与部分受信任代码调用堆栈上创建动态方法,则它不能访问私有成员中的类型的.NET Framework.NET Framework程序集,因为此类程序集是完全受信任。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.NET Framework assembly, because such assemblies are fully trusted.

如果restrictedSkipVisibilityfalse,会强制执行 JIT 可见性检查。If restrictedSkipVisibility is false, JIT visibility checks are enforced. 动态方法中的代码有权访问的公共类的公共方法,并尝试访问的是类型或成员,是否会引发异常privateprotected,或internalThe 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.

此构造函数指定方法属性MethodAttributes.PublicMethodAttributes.Static,并调用约定CallingConventions.StandardThis constructor specifies the method attributes MethodAttributes.Public and MethodAttributes.Static, and the calling convention CallingConventions.Standard.

备注

此构造函数中引入了 .NET Framework 3.5.NET Framework 3.5或更高版本。This constructor was introduced in the .NET Framework 3.5.NET Framework 3.5 or later.

另请参阅

DynamicMethod(String, Type, Type[], Module) DynamicMethod(String, Type, Type[], Module) DynamicMethod(String, Type, Type[], Module) 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.

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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module Module Module Module

一个 Module,表示动态方法将与之逻辑关联的模块。A Module representing the module with which the dynamic method is to be logically associated.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- m 是为动态方法提供匿名承载的模块。m is a module that provides anonymous hosting for dynamic methods.

namenullname is null.

- 或 --or- mnullm is null.

returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

示例

下面的代码示例创建动态方法采用两个参数。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. 该示例完成方法创建委托,调用委托,它具有不同的参数,并最后调用动态方法使用Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)方法。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
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
'

注解

此构造函数指定方法的特性MethodAttributes.PublicMethodAttributes.Static,调用约定CallingConventions.Standard,和不跳过在实时 (JIT) 可见性检查。This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, calling convention CallingConventions.Standard, and does not skip just-in-time (JIT) visibility checks.

使用此构造函数创建的动态方法有权访问公共和internal(Friend在 Visual Basic 中) 包含在模块中的所有类型的成员mThe 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.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:m是以外调用模块,以及对需求的模块ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与非调用模块的模块相关联。to associate the dynamic method with a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

DynamicMethod(String, Type, Type[], Type) DynamicMethod(String, Type, Type[], Type) DynamicMethod(String, Type, Type[], Type) 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.

public:
 DynamicMethod(System::String ^ name, Type ^ returnType, cli::array <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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type Type Type Type

一个 Type,动态方法与其逻辑关联。A Type with which the dynamic method is logically associated. 动态方法可以访问类型的所有成员。The dynamic method has access to all members of the type.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- owner 是一个接口、一个数组、一个开放式泛型类型或一个泛型类型或方法的类型参数。owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

namenullname is null.

- 或 --or- ownernullowner is null.

returnTypenull,或者为 IsByRef 返回 true 的类型。returnType is null, or is a type for which IsByRef returns true.

示例

下面的代码示例创建DynamicMethod这就是逻辑上相关联的类型。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.

代码示例定义一个名为Example使用私有字段,一个类名为DerivedFromExample派生的第一个类,名为的委托类型UseLikeStatic返回Int32类型的参数,且ExampleInt32,和一个名为的委托类型UseLikeInstance,它返回Int32具有一个类型参数和Int32The 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,然后创建两个委托。The example code creates an instance of Example and then creates two delegates. 第一个是类型的UseLikeStatic,其中包含与动态方法相同的参数。The first is of type UseLikeStatic, which has the same parameters as the dynamic method. 第二个属于类型UseLikeInstance,其中缺少第一个参数 (类型的Example)。The second is of type UseLikeInstance, which lacks the first parameter (of type Example). 使用创建此委托CreateDelegate(Type, Object)方法重载; 第二个参数的方法重载是的一个实例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. 每当调用该委托,动态方法都作用于的绑定实例ExampleWhenever 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调用委托时,以便这两个委托都作用于的同一个实例ExampleThen 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' 

注解

使用此构造函数创建的动态方法有权访问该类型的所有成员owner,并为公共和internal(Friend在 Visual Basic 中) 中包含的模块的所有其他类型的成员ownerThe 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.

此构造函数指定方法的特性MethodAttributes.PublicMethodAttributes.Static,调用约定CallingConventions.Standard,和不跳过在实时 (JIT) 可见性检查。This constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, calling convention CallingConventions.Standard, and does not skip just-in-time (JIT) visibility checks.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:owner所在的模块之外调用模块,以及对需求ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与模块不同于调用模块中的类型相关联。to associate the dynamic method with a type in a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

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

创建一个对模块全局有效的动态方法,指定方法名称、返回类型、参数类型和模块,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module Module Module Module

一个 Module,表示动态方法将与之逻辑关联的模块。A Module representing the module with which the dynamic method is to be logically associated.

skipVisibility
Boolean Boolean Boolean Boolean

要跳过对动态方法的 MSIL 访问的类型和成员的 JIT 可见性检查,则为 truetrue to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- m 是为动态方法提供匿名承载的模块。m is a module that provides anonymous hosting for dynamic methods.

namenullname is null.

- 或 --or- mnullm is null.

returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

注解

此构造函数指定方法的特性MethodAttributes.PublicMethodAttributes.Static,、 调用约定CallingConventions.StandardThis constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, and calling convention CallingConventions.Standard.

使用此构造函数创建的动态方法有权访问公共和internal(Friend在 Visual Basic 中) 包含模块中的所有类型的成员mThe 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. 跳过 JIT 编译器的可见性检查允许动态方法访问的所有其他类型的私有和受保护成员。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.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:m是以外调用模块,以及对需求的模块ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与非调用模块的模块相关联。to associate the dynamic method with a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

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

创建一个动态方法,指定方法名称、返回类型、参数类型、动态方法逻辑关联的类型,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type Type Type Type

一个 Type,动态方法与其逻辑关联。A Type with which the dynamic method is logically associated. 动态方法可以访问类型的所有成员。The dynamic method has access to all members of the type.

skipVisibility
Boolean Boolean Boolean Boolean

要跳过动态方法的 MSIL 访问的类型和成员的 JIT 可见性检查,则为 true;否则为 falsetrue to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- owner 是一个接口、一个数组、一个开放式泛型类型或一个泛型类型或方法的类型参数。owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

namenullname is null.

- 或 --or- ownernullowner is null.

returnTypenull,或者为 IsByRef 返回 true 的类型。returnType is null, or is a type for which IsByRef returns true.

注解

使用此构造函数创建的动态方法有权访问该类型的所有成员owner,并为公共和internal(Friend在 Visual Basic 中) 中包含的模块的所有其他类型的成员ownerThe 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. 跳过 JIT 编译器的可见性检查允许动态方法访问的所有其他类型的私有和受保护成员。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.

此构造函数指定方法的特性MethodAttributes.PublicMethodAttributes.Static,、 调用约定CallingConventions.StandardThis constructor specifies method attributes MethodAttributes.Public and MethodAttributes.Static, and calling convention CallingConventions.Standard.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:owner所在的模块之外调用模块,以及对需求ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与模块不同于调用模块中的类型相关联。to associate the dynamic method with a type in a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

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

创建一个对模块全局有效的动态方法,指定方法名称、属性、调用约定、返回类型、参数类型和模块,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

MethodAttributes 值的按位组合,指定动态方法的属性。A bitwise combination of MethodAttributes values that specifies the attributes of the dynamic method. 允许的唯一组合为 PublicStaticThe only combination allowed is Public and Static.

callingConvention
CallingConventions CallingConventions CallingConventions CallingConventions

动态方法的调用约定。The calling convention for the dynamic method. 必须为 StandardMust be Standard.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

m
Module Module Module Module

一个 Module,表示动态方法将与之逻辑关联的模块。A Module representing the module with which the dynamic method is to be logically associated.

skipVisibility
Boolean Boolean Boolean Boolean

要跳过动态方法的 MSIL 访问的类型和成员的 JIT 可见性检查,则为 true;否则为 falsetrue to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- m 是为动态方法提供匿名承载的模块。m is a module that provides anonymous hosting for dynamic methods.

namenullname is null.

- 或 --or- mnullm is null.

attributes 是标志的组合,而不是 PublicStatic 的组合。attributes is a combination of flags other than Public and Static.

- 或 --or- callingConvention 不是 StandardcallingConvention is not Standard.

- 或 --or- returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

注解

使用此构造函数创建的动态方法有权访问公共和internal(Friend在 Visual Basic 中) 包含在模块中的所有公共和内部类型的成员mThe 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.

跳过 JIT 编译器的可见性检查允许动态方法访问的所有其他类型的模块中和所有其他程序集中的私有和受保护成员。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.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:m是以外调用模块,以及对需求的模块ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与非调用模块的模块相关联。to associate the dynamic method with a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

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

创建一个动态方法,指定方法名称、特性、调用约定、返回类型、参数类型、动态方法逻辑关联的类型,并指定动态方法的 Microsoft 中间语言 (MSIL) 访问的类型和成员是否应跳过实时 (JIT) 可见性检查。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);
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)

参数

name
String String String String

动态方法的名称。The name of the dynamic method. 它可以是长度为零的字符串,但不能为 nullThis can be a zero-length string, but it cannot be null.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

MethodAttributes 值的按位组合,指定动态方法的属性。A bitwise combination of MethodAttributes values that specifies the attributes of the dynamic method. 允许的唯一组合为 PublicStaticThe only combination allowed is Public and Static.

callingConvention
CallingConventions CallingConventions CallingConventions CallingConventions

动态方法的调用约定。The calling convention for the dynamic method. 必须为 StandardMust be Standard.

returnType
Type Type Type Type

一个 Type 对象,用于指定动态方法的返回类型,如果此方法没有返回类型,则为 nullA Type object that specifies the return type of the dynamic method, or null if the method has no return type.

parameterTypes
Type[]

指定动态方法的参数类型的 Type 对象数组,如果此方法不具有任何参数,则为 nullAn array of Type objects specifying the types of the parameters of the dynamic method, or null if the method has no parameters.

owner
Type Type Type Type

一个 Type,动态方法与其逻辑关联。A Type with which the dynamic method is logically associated. 动态方法可以访问类型的所有成员。The dynamic method has access to all members of the type.

skipVisibility
Boolean Boolean Boolean Boolean

要跳过动态方法的 MSIL 访问的类型和成员的 JIT 可见性检查,则为 true;否则为 falsetrue to skip JIT visibility checks on types and members accessed by the MSIL of the dynamic method; otherwise, false.

异常

parameterTypes 的元素为 nullVoidAn element of parameterTypes is null or Void.

- 或 --or- owner 是一个接口、一个数组、一个开放式泛型类型或一个泛型类型或方法的类型参数。owner is an interface, an array, an open generic type, or a type parameter of a generic type or method.

namenullname is null.

- 或 --or- ownernullowner is null.

attributes 是标志的组合,而不是 PublicStatic 的组合。attributes is a combination of flags other than Public and Static.

- 或 --or- callingConvention 不是 StandardcallingConvention is not Standard.

- 或 --or- returnType 是一种 IsByRef 为其返回 true 的类型。returnType is a type for which IsByRef returns true.

注解

动态方法是包含类型的模块的全局ownerThe dynamic method is global to the module that contains the type owner. 它有权访问该类型的所有成员ownerIt has access to all members of the type owner.

使用此构造函数创建的动态方法有权访问该类型的所有成员owner,并为公共和internal(Friend在 Visual Basic 中) 中包含的模块包含的所有类型的成员ownerThe 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. 跳过 JIT 编译器的可见性检查允许动态方法访问的所有其他类型的私有和受保护成员。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.

备注

对于向后兼容,此构造函数要求SecurityPermissionSecurityPermissionFlag.ControlEvidence标志,如果是两个以下条件,则返回 true:owner所在的模块之外调用模块,以及对需求ReflectionPermissionReflectionPermissionFlag.MemberAccess标志已失败。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. 如果对需求SecurityPermission成功,允许执行该操作。If the demand for SecurityPermission succeeds, the operation is allowed.

备注

从开始.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1,此成员不再需要ReflectionPermissionReflectionPermissionFlag.ReflectionEmit标志。Starting with the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, this member no longer requires ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. (请参阅反射发出中的安全问题。)若要使用此功能,应用程序应为 .NET Framework 3.5.NET Framework 3.5 或更高版本。(See Security Issues in Reflection Emit.) To use this functionality, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

安全性

ReflectionPermission
若要将动态方法与模块不同于调用模块中的类型相关联。to associate the dynamic method with a type in a module other than the calling module. 关联枚举:RestrictedMemberAccessAssociated enumeration: RestrictedMemberAccess.

另请参阅

适用于