DynamicMethod DynamicMethod DynamicMethod DynamicMethod Class

定义

定义并表示一种可编译、执行和丢弃的动态方法。Defines and represents a dynamic method that can be compiled, executed, and discarded. 丢弃的方法可用于垃圾回收。Discarded methods are available for garbage collection.

public ref class DynamicMethod sealed : System::Reflection::MethodInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DynamicMethod : System.Reflection.MethodInfo
type DynamicMethod = class
    inherit MethodInfo
Public NotInheritable Class DynamicMethod
Inherits MethodInfo
继承
属性

示例

下面的代码示例创建一个带有两个参数的动态方法。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方法调用动态方法。The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the Invoke method.

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

// Declare a delegate type that can be used to execute the completed
// dynamic method. 
private delegate int HelloDelegate(String^ msg, int ret);

void main()
{
    // Create an array that specifies the types of the parameters
    // of the dynamic method. This dynamic method has a String
    // parameter and an Integer parameter.
    array<Type^>^ helloArgs = { String::typeid, int::typeid };

    // 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 String class.
    DynamicMethod^ hello = gcnew DynamicMethod("Hello", 
        int::typeid, 
        helloArgs, 
        String::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,
    // using a stream size larger than the IL that will be
    // emitted.
    ILGenerator^ il = hello->GetILGenerator(256);
    // 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, nullptr);
    // 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);

    // Add parameter information to the dynamic method. (This is not
    // necessary, but can be useful for debugging.) For each parameter,
    // identified by position, supply the parameter attributes and a 
    // parameter name.
    hello->DefineParameter(1, ParameterAttributes::In, "message");
    hello->DefineParameter(2, ParameterAttributes::In, "valueToReturn");

    // Create a delegate that represents the dynamic method. This
    // action completes the method. Any further attempts to
    // change the method are ignored.
    HelloDelegate^ hi = 
        (HelloDelegate^) hello->CreateDelegate(HelloDelegate::typeid);

    // Use the delegate to execute the dynamic method.
    Console::WriteLine("\r\nUse the delegate to execute the dynamic method:");
    int retval = hi("\r\nHello, World!", 42);
    Console::WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

    // Execute it again, with different arguments.
    retval = hi("\r\nHi, Mom!", 5280);
    Console::WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned: " + retval);

    Console::WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
    // Create an array of arguments to use with the Invoke method.
    array<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 value-type arguments
    // must be boxed.
    Object^ objRet = hello->Invoke(nullptr, BindingFlags::ExactBinding, nullptr, invokeArgs, gcnew CultureInfo("en-us"));
    Console::WriteLine("hello.Invoke returned: " + objRet);

    Console::WriteLine("\r\n ----- Display information about the dynamic method -----");
    // Display MethodAttributes for the dynamic method, set when 
    // the dynamic method was created.
    Console::WriteLine("\r\nMethod Attributes: {0}", hello->Attributes);

    // Display the calling convention of the dynamic method, set when the 
    // dynamic method was created.
    Console::WriteLine("\r\nCalling convention: {0}", hello->CallingConvention);

    // Display the declaring type, which is always null for dynamic
    // methods.
    if (hello->DeclaringType == nullptr)
    {
        Console::WriteLine("\r\nDeclaringType is always null for dynamic methods.");
    }
    else
    {
        Console::WriteLine("DeclaringType: {0}", hello->DeclaringType);
    }

    // Display the default value for InitLocals.
    if (hello->InitLocals)
    {
        Console::Write("\r\nThis method contains verifiable code.");
    }
    else
    {
        Console::Write("\r\nThis method contains unverifiable code.");
    }
    Console::WriteLine(" (InitLocals = {0})", hello->InitLocals);

    // Display the module specified when the dynamic method was created.
    Console::WriteLine("\r\nModule: {0}", hello->Module);

    // Display the name specified when the dynamic method was created.
    // Note that the name can be blank.
    Console::WriteLine("\r\nName: {0}", hello->Name);

    // For dynamic methods, the reflected type is always null.
    if (hello->ReflectedType == nullptr)
    {
        Console::WriteLine("\r\nReflectedType is null.");
    }
    else
    {
        Console::WriteLine("\r\nReflectedType: {0}", hello->ReflectedType);
    }

    if (hello->ReturnParameter == nullptr)
    {
        Console::WriteLine("\r\nMethod has no return parameter.");
    }
    else
    {
        Console::WriteLine("\r\nReturn parameter: {0}", hello->ReturnParameter);
    }

    // If the method has no return type, ReturnType is System.Void.
    Console::WriteLine("\r\nReturn type: {0}", hello->ReturnType);

    // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
    // that can be used to enumerate the custom attributes of the
    // return value. At present, there is no way to set such custom
    // attributes, so the list is empty.
    if (hello->ReturnType == Void::typeid)
    {
        Console::WriteLine("The method has no return type.");
    }
    else
    {
        ICustomAttributeProvider^ caProvider = hello->ReturnTypeCustomAttributes;
        array<Object^>^ returnAttributes = caProvider->GetCustomAttributes(true);
        if (returnAttributes->Length == 0)
        {
            Console::WriteLine("\r\nThe return type has no custom attributes.");
        }
        else
        {
            Console::WriteLine("\r\nThe return type has the following custom attributes:");
            for each (Object^ attr in returnAttributes)
            {
                Console::WriteLine("\t{0}", attr->ToString());
            }
        }
    }

    Console::WriteLine("\r\nToString: {0}", hello->ToString());

    // Display parameter information.
    array<ParameterInfo^>^ parameters = hello->GetParameters();
    Console::WriteLine("\r\nParameters: name, type, ParameterAttributes");
    for each (ParameterInfo^ p in parameters)
    {
        Console::WriteLine("\t{0}, {1}, {2}", 
            p->Name, p->ParameterType, p->Attributes);
    }
}

/* This code example produces the following output:

Use the delegate to execute the dynamic method:

Hello, World!
Invoking delegate hi("Hello, World!", 42) returned: 42

Hi, Mom!
Invoking delegate hi("Hi, Mom!", 5280) returned: 5280

Use the Invoke method to execute the dynamic method:

Hello, World!
hello.Invoke returned: 42

 ----- Display information about the dynamic method -----

Method Attributes: PrivateScope, Public, Static

Calling convention: Standard

DeclaringType is always null for dynamic methods.

This method contains verifiable code. (InitLocals = True)

Module: CommonLanguageRuntimeLibrary

Name: Hello

ReflectedType is null.

Method has no return parameter.

Return type: System.Int32

The return type has no custom attributes.

ToString: Int32 Hello(System.String, Int32)

Parameters: name, type, ParameterAttributes
        message, System.String, In
        valueToReturn, System.Int32, In
 */
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;

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

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

        // 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 String class.
        DynamicMethod hello = new DynamicMethod("Hello", 
            typeof(int), 
            helloArgs, 
            typeof(string).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,
        // using a stream size larger than the IL that will be
        // emitted.
        ILGenerator il = hello.GetILGenerator(256);
        // 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);

        // Add parameter information to the dynamic method. (This is not
        // necessary, but can be useful for debugging.) For each parameter,
        // identified by position, supply the parameter attributes and a 
        // parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message");
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn");

        // Create a delegate that represents the dynamic method. This
        // action completes the method. Any further attempts to
        // change the method are ignored.
        HelloDelegate hi = 
            (HelloDelegate) hello.CreateDelegate(typeof(HelloDelegate));

        // Use the delegate to execute the dynamic method.
        Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
        int retval = hi("\r\nHello, World!", 42);
        Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

        // Execute it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned: " + retval);

        Console.WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
        // 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 value-type arguments
        // must be boxed.
        object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));
        Console.WriteLine("hello.Invoke returned: " + objRet);

        Console.WriteLine("\r\n ----- Display information about the dynamic method -----");
        // Display MethodAttributes for the dynamic method, set when 
        // the dynamic method was created.
        Console.WriteLine("\r\nMethod Attributes: {0}", hello.Attributes);

        // Display the calling convention of the dynamic method, set when the 
        // dynamic method was created.
        Console.WriteLine("\r\nCalling convention: {0}", hello.CallingConvention);

        // Display the declaring type, which is always null for dynamic
        // methods.
        if (hello.DeclaringType == null)
        {
            Console.WriteLine("\r\nDeclaringType is always null for dynamic methods.");
        }
        else
        {
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType);
        }

        // Display the default value for InitLocals.
        if (hello.InitLocals)
        {
            Console.Write("\r\nThis method contains verifiable code.");
        }
        else
        {
            Console.Write("\r\nThis method contains unverifiable code.");
        }
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals);

        // Display the module specified when the dynamic method was created.
        Console.WriteLine("\r\nModule: {0}", hello.Module);

        // Display the name specified when the dynamic method was created.
        // Note that the name can be blank.
        Console.WriteLine("\r\nName: {0}", hello.Name);

        // For dynamic methods, the reflected type is always null.
        if (hello.ReflectedType == null)
        {
            Console.WriteLine("\r\nReflectedType is null.");
        }
        else
        {
            Console.WriteLine("\r\nReflectedType: {0}", hello.ReflectedType);
        }

        if (hello.ReturnParameter == null)
        {
            Console.WriteLine("\r\nMethod has no return parameter.");
        }
        else
        {
            Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
        }

        // If the method has no return type, ReturnType is System.Void.
        Console.WriteLine("\r\nReturn type: {0}", hello.ReturnType);

        // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        // that can be used to enumerate the custom attributes of the
        // return value. At present, there is no way to set such custom
        // attributes, so the list is empty.
        if (hello.ReturnType == typeof(void))
        {
            Console.WriteLine("The method has no return type.");
        }
        else
        {
            ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
            object[] returnAttributes = caProvider.GetCustomAttributes(true);
            if (returnAttributes.Length == 0)
            {
                Console.WriteLine("\r\nThe return type has no custom attributes.");
            }
            else
            {
                Console.WriteLine("\r\nThe return type has the following custom attributes:");
                foreach( object attr in returnAttributes )
                {
                    Console.WriteLine("\t{0}", attr.ToString());
                }
            }
        }

        Console.WriteLine("\r\nToString: {0}", hello.ToString());

        // Display parameter information.
        ParameterInfo[] parameters = hello.GetParameters();
        Console.WriteLine("\r\nParameters: name, type, ParameterAttributes");
        foreach( ParameterInfo p in parameters )
        {
            Console.WriteLine("\t{0}, {1}, {2}", 
                p.Name, p.ParameterType, p.Attributes);
        }
    }
}

/* This code example produces the following output:

Use the delegate to execute the dynamic method:

Hello, World!
Invoking delegate hi("Hello, World!", 42) returned: 42

Hi, Mom!
Invoking delegate hi("Hi, Mom!", 5280) returned: 5280

Use the Invoke method to execute the dynamic method:

Hello, World!
hello.Invoke returned: 42

 ----- Display information about the dynamic method -----

Method Attributes: PrivateScope, Public, Static

Calling convention: Standard

DeclaringType is always null for dynamic methods.

This method contains verifiable code. (InitLocals = True)

Module: CommonLanguageRuntimeLibrary

Name: Hello

ReflectedType is null.

Method has no return parameter.

Return type: System.Int32

The return type has no custom attributes.

ToString: Int32 Hello(System.String, Int32)

Parameters: name, type, ParameterAttributes
        message, System.String, In
        valueToReturn, System.Int32, In
 */
Imports System
Imports System.Reflection
Imports System.Reflection.Emit
Imports Microsoft.VisualBasic
Imports System.Globalization

Public Class Test
    ' Declare a delegate type that can be used to execute the completed
    ' dynamic method. 
    Private Delegate Function HelloDelegate(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 dynamic 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 String class.
        Dim hello As New DynamicMethod("Hello", _
            GetType(Integer), _
            helloArgs, _
            GetType(String).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,
        ' using a stream size larger than the IL that will be
        ' emitted.
        Dim il As ILGenerator = hello.GetILGenerator(256)
        ' 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)

        ' Add parameter information to the dynamic method. (This is not
        ' necessary, but can be useful for debugging.) For each parameter,
        ' identified by position, supply the parameter attributes and a 
        ' parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message")
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn")

        ' Create a delegate that represents the dynamic method. This
        ' action completes the method. Any further attempts to
        ' change the method are ignored.
	Dim hi As HelloDelegate = _
            CType(hello.CreateDelegate(GetType(HelloDelegate)), HelloDelegate)

        ' Use the delegate to execute the dynamic method.
        Console.WriteLine(vbCrLf & "Use the delegate to execute the dynamic method:")
        Dim retval As Integer = hi(vbCrLf & "Hello, World!", 42)
        Console.WriteLine("Invoking delegate hi(""Hello, World!"", 42) returned: " _
            & retval & ".")

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

        Console.WriteLine(vbCrLf & "Use the Invoke method to execute the dynamic method:")
        ' 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 value-type arguments
        ' must be boxed.
        Dim objRet As Object = hello.Invoke(Nothing, _
            BindingFlags.ExactBinding, Nothing, invokeArgs, _
            New CultureInfo("en-us"))
        Console.WriteLine("hello.Invoke returned: {0}", objRet)

        Console.WriteLine(vbCrLf & _
            " ----- Display information about the dynamic method -----")
        ' Display MethodAttributes for the dynamic method, set when 
        ' the dynamic method was created.
        Console.WriteLine(vbCrLf & "Method Attributes: {0}", _
            hello.Attributes)

        ' Display the calling convention of the dynamic method, set when the 
        ' dynamic method was created.
        Console.WriteLine(vbCrLf & "Calling convention: {0}", _ 
            hello.CallingConvention)

        ' Display the declaring type, which is always Nothing for dynamic
        ' methods.
        If hello.DeclaringType Is Nothing Then
            Console.WriteLine(vbCrLf & "DeclaringType is always Nothing for dynamic methods.")
        Else
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType)
        End If

        ' Display the default value for InitLocals.
        If hello.InitLocals Then
            Console.Write(vbCrLf & "This method contains verifiable code.")
        Else
            Console.Write(vbCrLf & "This method contains unverifiable code.")
        End If
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals)

        ' Display the module specified when the dynamic method was created.
        Console.WriteLine(vbCrLf & "Module: {0}", hello.Module)

        ' Display the name specified when the dynamic method was created.
        ' Note that the name can be blank.
        Console.WriteLine(vbCrLf & "Name: {0}", hello.Name)

        ' For dynamic methods, the reflected type is always Nothing.
        If hello.ReflectedType Is Nothing Then
            Console.WriteLine(vbCrLf & "ReflectedType is Nothing.")
        Else
            Console.WriteLine(vbCrLf & "ReflectedType: {0}", _
                hello.ReflectedType)
        End If

        If hello.ReturnParameter Is Nothing Then
            Console.WriteLine(vbCrLf & "Method has no return parameter.")
        Else
            Console.WriteLine(vbCrLf & "Return parameter: {0}", _
                hello.ReturnParameter)
        End If

        ' If the method has no return type, ReturnType is System.Void.
        Console.WriteLine(vbCrLf & "Return type: {0}", hello.ReturnType)           

        ' ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        ' that can be used to enumerate the custom attributes of the
        ' return value. At present, there is no way to set such custom
        ' attributes, so the list is empty.
        If hello.ReturnType Is GetType(System.Void) Then
            Console.WriteLine("The method has no return type.")
        Else
            Dim caProvider As ICustomAttributeProvider = _
                hello.ReturnTypeCustomAttributes
            Dim returnAttributes() As Object = _
                caProvider.GetCustomAttributes(True)
            If returnAttributes.Length = 0 Then
                Console.WriteLine(vbCrLf _
                    & "The return type has no custom attributes.")
            Else
                Console.WriteLine(vbCrLf _
                    & "The return type has the following custom attributes:")
                For Each attr As Object In returnAttributes
                    Console.WriteLine(vbTab & attr.ToString())
                Next attr
            End If
        End If

        Console.WriteLine(vbCrLf & "ToString: " & hello.ToString())

        ' Display parameter information.
        Dim parameters() As ParameterInfo = hello.GetParameters()
        Console.WriteLine(vbCrLf & "Parameters: name, type, ParameterAttributes")
        For Each p As ParameterInfo In parameters
            Console.WriteLine(vbTab & "{0}, {1}, {2}", _ 
                p.Name, p.ParameterType, p.Attributes)
        Next p
    End Sub
End Class

' This code example produces the following output:
'
'Use the delegate to execute the dynamic method:
'
'Hello, World!
'Invoking delegate hi("Hello, World!", 42) returned: 42.
'
'Hi, Mom!
'Invoking delegate hi("Hi, Mom!", 5280) returned: 5280.
'
'Use the Invoke method to execute the dynamic method:
'
'Hello, World!
'hello.Invoke returned: 42
'
' ----- Display information about the dynamic method -----
'
'Method Attributes: PrivateScope, Public, Static
'
'Calling convention: Standard
'
'DeclaringType is always Nothing for dynamic methods.
'
'This method contains verifiable code. (InitLocals = True)
'
'Module: CommonLanguageRuntimeLibrary
'
'Name: Hello
'
'ReflectedType is Nothing.
'
'Method has no return parameter.
'
'Return type: System.Int32
'
'The return type has no custom attributes.
'
'ToString: Int32 Hello(System.String, Int32)
'
'Parameters: name, type, ParameterAttributes
'        message, System.String, In
'        valueToReturn, System.Int32, In

注解

您可以使用DynamicMethod类在运行时生成和执行方法, 而不必生成动态程序集和动态类型来包含方法。You can use the DynamicMethod class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. 回收DynamicMethod对象时, 由实时 (JIT) 编译器创建的可执行代码将被回收。The executable code created by the just-in-time (JIT) compiler is reclaimed when the DynamicMethod object is reclaimed. 动态方法是生成和执行少量代码的最有效方法。Dynamic methods are the most efficient way to generate and execute small amounts of code.

动态方法可以是匿名承载的, 也可以逻辑上与模块或类型相关联。A dynamic method can be anonymously hosted, or it can be logically associated with a module or with a type.

  • 如果动态方法是匿名承载的, 则该方法位于系统提供的程序集中, 因此与其他代码隔离。If the dynamic method is anonymously hosted, it is located in a system-provided assembly, and therefore is isolated from other code. 默认情况下, 它无权访问任何非公共数据。By default, it does not have access to any non-public data. 匿名托管的动态方法可以具有跳过 JIT 编译器的可见性检查的受限能力, 前提是该方法ReflectionPermission已被ReflectionPermissionFlag.RestrictedMemberAccess授予标志。An anonymously hosted dynamic method can have restricted ability to skip the JIT compiler's visibility checks, if it has been granted ReflectionPermission with the ReflectionPermissionFlag.RestrictedMemberAccess flag. 动态方法访问其非公共成员的程序集的信任级别必须等于发出动态方法的调用堆栈的信任级别 (或的子集)。The trust level of the assembly whose non-public members are accessed by the dynamic method must be equal to, or a subset of, the trust level of the call stack that emitted the dynamic method. 有关匿名承载的动态方法的详细信息, 请参阅演练:在部分信任方案中发出代码。For more information about anonymously hosted dynamic methods, see Walkthrough: Emitting Code in Partial Trust Scenarios.

  • 如果动态方法与指定的模块相关联, 动态方法将在该模块中有效地成为全局方法。If the dynamic method is associated with a module that you specify, the dynamic method is effectively global to that module. 它可以访问模块中的所有类型以及这些internal类型Friend的所有 (在 Visual Basic 中) 成员。It can access all types in the module and all internal (Friend in Visual Basic) members of the types. 无论是否已创建模块, 都可以将动态方法与任何模块相关联, 前提是包含代码的调用ReflectionPermission堆栈可以RestrictedMemberAccess满足带标志的请求。You can associate a dynamic method with any module, regardless of whether you created the module, provided that a demand for ReflectionPermission with the RestrictedMemberAccess flag can be satisfied by the call stack that includes your code. 如果该ReflectionPermissionFlag.MemberAccess标志包含在 grant 中, 则动态方法可以跳过 JIT 编译器的可见性检查并访问在该模块中声明的所有类型的私有数据或任何程序集中的任何其他模块。If the ReflectionPermissionFlag.MemberAccess flag is included in the grant, the dynamic method can skip the JIT compiler's visibility checks and access the private data of all types declared in the module or in any other module in any assembly.

    备注

    指定与动态方法关联的模块时, 该模块不得位于系统提供的程序集中, 该程序集用于匿名托管。When you specify the module with which a dynamic method is associated, that module must not be in the system-provided assembly that is used for anonymous hosting.

  • 如果动态方法与指定的类型相关联, 则它有权访问该类型的所有成员, 而不考虑访问级别。If the dynamic method is associated with a type that you specify, it has access to all members of the type, regardless of access level. 此外, 还可以跳过 JIT 可见性检查。In addition, JIT visibility checks can be skipped. 这为动态方法提供对在同一模块中或在任何程序集中的任何其他模块中声明的其他类型的私有数据的访问。This gives the dynamic method access to the private data of other types declared in the same module or in any other module in any assembly. 可以将动态方法与任何类型相关联, 但必须ReflectionPermission RestrictedMemberAccess同时向代码授予和MemberAccess标志。You can associate a dynamic method with any type, but your code must be granted ReflectionPermission with both the RestrictedMemberAccess and MemberAccess flags.

下表显示了匿名托管的动态方法可访问的类型和成员 (带有和不带 JIT 可见性检查), 具体ReflectionPermission取决于RestrictedMemberAccess是否授予了标志。The following table shows which types and members are accessible to an anonymously hosted dynamic method, with and without JIT visibility checks, depending on whether ReflectionPermission with the RestrictedMemberAccess flag is granted.

没有 RestrictedMemberAccessWithout RestrictedMemberAccess 通过 RestrictedMemberAccessWith RestrictedMemberAccess
不跳过 JIT 可见性检查Without skipping JIT visibility checks 任何程序集中公共类型的公共成员。Public members of public types in any assembly. 任何程序集中公共类型的公共成员。Public members of public types in any assembly.
跳过 JIT 可见性检查, 但有限制Skipping JIT visibility checks, with restrictions 任何程序集中公共类型的公共成员。Public members of public types in any assembly. 所有类型的所有成员, 仅在其信任级别等于或小于发出动态方法的程序集的信任级别的程序集中。All members of all types, only in assemblies whose trust levels are equal to or less than the trust level of the assembly that emitted the dynamic method.

备注

.NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1之前, 发出ReflectionPermissionFlag.ReflectionEmit标记所需ReflectionPermission的代码。Prior to the .NET Framework 2.0 Service Pack 1.NET Framework 2.0 Service Pack 1, emitting code required ReflectionPermission with the ReflectionPermissionFlag.ReflectionEmit flag. 默认情况下, 此权限包含在 FullTrust 和 LocalIntranet 命名权限集中, 而不是在 Internet 权限集中。This permission is included by default in the FullTrust and LocalIntranet named permission sets, but not in the Internet permission set. 因此, .NET Framework.NET Framework在早期版本的库中, 只有当库SecurityCriticalAttribute具有Assert特性并为ReflectionEmit执行时, 才能与 Internet 权限一起使用。Therefore, in earlier versions of the .NET Framework.NET Framework a library can be used with Internet permissions only if it has the SecurityCriticalAttribute attribute and also executes an Assert for ReflectionEmit. 这种库需要进行仔细的安全检查,因为编码错误可能会导致安全漏洞。Such libraries require careful security review because coding errors could result in security holes. .NET Framework 2.0 SP1.NET Framework 2.0 SP1 允许以部分信任形式发出代码而无需发出任何安全请求,因为生成代码本身不是一项特权操作。The .NET Framework 2.0 SP1.NET Framework 2.0 SP1 allows code to be emitted in partial trust scenarios without issuing any security demands, because generating code is not inherently a privileged operation. 也就是说,生成的代码不会具有比发出它的程序集更多的权限。That is, the generated code has no more permissions than the assembly that emits it. 这使得发出代码的库是安全透明的,且不再需要断言 ReflectionEmit,这简化了编写安全库任务。This allows libraries that emit code to be security transparent and removes the need to assert ReflectionEmit, which simplifies the task of writing a secure library. 若要使用此功能, 应用程序应面向 .NET Framework 3.5.NET Framework 3.5或更高版本。To use this feature, your application should target the .NET Framework 3.5.NET Framework 3.5 or later.

下表显示了与模块或模块中的类型相关联的动态方法可以访问的类型和成员。The following table shows which types and members are accessible to a dynamic method that is associated with a module or with a type in a module.

与模块关联Associated with module 与类型关联Associated with type
不跳过 JIT 可见性检查Without skipping JIT visibility checks 模块中公共类型、内部类型和私有类型的公共和内部成员。Public and internal members of public, internal, and private types in the module.

任何程序集中公共类型的公共成员。Public members of public types in any assembly.
关联类型的所有成员。All members of the associated type. 模块中所有其他类型的公共和内部成员。Public and internal members of all the other types in the module.

任何程序集中公共类型的公共成员。Public members of public types in any assembly.
跳过 JIT 可见性检查Skipping JIT visibility checks 所有程序集中的所有类型的所有成员。All members of all types in any assembly. 所有程序集中的所有类型的所有成员。All members of all types in any assembly.

与模块关联的动态方法具有该模块的权限。A dynamic method that is associated with a module has the permissions of that module. 与某一类型关联的动态方法具有包含该类型的模块的权限。A dynamic method that is associated with a type has the permissions of the module containing that type.

动态方法及其参数无需命名, 但你可以指定名称来帮助进行调试。Dynamic methods and their parameters do not have to be named, but you can specify names to assist in debugging. 动态方法或其参数不支持自定义属性。Custom attributes are not supported on dynamic methods or their parameters.

尽管动态方法是static方法 (Shared Visual Basic 中的方法), 但中引入的.NET Framework 2.0.NET Framework 2.0委托绑定的宽松规则允许将动态方法绑定到对象, 以便在使用该委托实例调用。Although dynamic methods are static methods (Shared methods in Visual Basic), the relaxed rules for delegate binding introduced in the .NET Framework 2.0.NET Framework 2.0 allow a dynamic method to be bound to an object, so that it acts like an instance method when called using that delegate instance. 此示例演示了如何为CreateDelegate(Type, Object)方法重载提供此方法。An example that demonstrates this is provided for the CreateDelegate(Type, Object) method overload.

备注

在中.NET Framework 2.0.NET Framework 2.0, 动态方法不支持符号信息, 即局部变量名称和行号映射。In the .NET Framework 2.0.NET Framework 2.0, dynamic methods do not support symbol information, that is, local variable names and line-number mapping. 在将来的版本中可能会删除此限制。This limitation might be removed in a future version. 你可以在AssemblyBuilder开发过程中使用来简化生成的 Microsoft 中间语言 (MSIL) 的调试, 然后在最终部署过程中切换到动态ILGenerator方法, 因为这两种情况下的调用都是相同的。You can use AssemblyBuilder during development to simplify debugging the generated Microsoft intermediate language (MSIL), and then switch to dynamic methods during final deployment, because the ILGenerator calls are the same in both cases.

确认Verification

下面的列表汇总了动态方法可包含无法验证的代码的情况。The following list summarizes the conditions under which dynamic methods can contain unverifiable code. (例如, 如果动态方法的属性设置为, InitLocals则无法false对其进行验证。)(For example, a dynamic method is unverifiable if its InitLocals property is set to false.)

  • 与安全关键程序集关联的动态方法也是安全关键的, 可跳过验证。A dynamic method that is associated with a security-critical assembly is also security-critical, and can skip verification. 例如, 如果程序集不具有作为桌面应用程序运行的安全属性, 则运行时将其视为安全关键。For example, an assembly without security attributes that is run as a desktop application is treated as security-critical by the runtime. 如果将动态方法与程序集相关联, 则动态方法可能包含不可验证的代码。If you associate a dynamic method with the assembly, the dynamic method can contain unverifiable code.

  • 如果包含不可验证代码的动态方法与具有级别1透明度的程序集相关联, 则实时 (JIT) 编译器将注入安全要求。If a dynamic method that contains unverifiable code is associated with an assembly that has level 1 transparency, the just-in-time (JIT) compiler injects a security demand. 仅当动态方法由完全受信任的代码执行时, 请求才会成功。The demand succeeds only if the dynamic method is executed by fully trusted code. 请参阅安全透明代码, 级别 1See Security-Transparent Code, Level 1.

  • 如果包含不可验证代码的动态方法与具有2级透明度 (如 mscorlib.dll) 的程序集相关联, 则它会引发异常 (由 JIT 编译器注入), 而不是发出安全要求。If a dynamic method that contains unverifiable code is associated with an assembly that has level 2 transparency (such as mscorlib.dll), it throws an exception (injected by the JIT compiler) instead of making a security demand. 请参阅安全透明代码, 级别 2See Security-Transparent Code, Level 2.

  • 包含不可验证的代码的匿名托管动态方法始终引发异常。An anonymously hosted dynamic method that contains unverifiable code always throws an exception. 即使它是由完全受信任的代码创建和执行的, 它也永远不会跳过验证。It can never skip verification, even if it is created and executed by fully trusted code.

对于不可验证的代码引发的异常会根据动态方法的调用方式而有所不同。The exception that is thrown for unverifiable code varies depending on the way the dynamic method is invoked. 如果使用从CreateDelegate方法返回的委托调用动态方法VerificationException , 则将引发。If you invoke a dynamic method by using a delegate returned from the CreateDelegate method, a VerificationException is thrown. 如果通过使用Invoke方法调用动态方法TargetInvocationException , 则将引发与内部VerificationException的。If you invoke the dynamic method by using the Invoke method, a TargetInvocationException is thrown with an inner VerificationException.

构造函数

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.

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[], 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) 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[], 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.

属性

Attributes Attributes Attributes Attributes

获取创建动态方法时指定的属性。Gets the attributes specified when the dynamic method was created.

CallingConvention CallingConvention CallingConvention CallingConvention

获取创建动态方法时指定的调用约定。Gets the calling convention specified when the dynamic method was created.

ContainsGenericParameters ContainsGenericParameters ContainsGenericParameters ContainsGenericParameters

获取一个值,该值指示泛型方法是否包含未赋值的泛型类型参数。Gets a value indicating whether the generic method contains unassigned generic type parameters.

(Inherited from MethodBase)
CustomAttributes CustomAttributes CustomAttributes CustomAttributes

获取包含此成员自定义属性的集合。Gets a collection that contains this member's custom attributes.

(Inherited from MemberInfo)
DeclaringType DeclaringType DeclaringType DeclaringType

获取声明方法的类型,对于动态方法,类型始终为 nullGets the type that declares the method, which is always null for dynamic methods.

InitLocals InitLocals InitLocals InitLocals

获取或设置一个值,该值指示方法中的局部变量是否初始化为零。Gets or sets a value indicating whether the local variables in the method are zero-initialized.

IsAbstract IsAbstract IsAbstract IsAbstract

获取一个值,该值指示此方法是否为抽象方法。Gets a value indicating whether the method is abstract.

(Inherited from MethodBase)
IsAssembly IsAssembly IsAssembly IsAssembly

获取一个值,该值指示此方法或构造函数的潜在可见性是否由 Assembly 描述;也就是说,此方法或构造函数只对同一程序集中的其他类型可见,而对该程序集以外的派生类型则不可见。Gets a value indicating whether the potential visibility of this method or constructor is described by Assembly; that is, the method or constructor is visible at most to other types in the same assembly, and is not visible to derived types outside the assembly.

(Inherited from MethodBase)
IsCollectible IsCollectible IsCollectible IsCollectible

获取一个值,该值指示此 MemberInfo 对象是否是包含在可回收的 AssemblyLoadContext 中的程序集的一部分。Gets a value that indicates whether this MemberInfo object is part of an assembly held in a collectible AssemblyLoadContext.

(Inherited from MemberInfo)
IsConstructedGenericMethod IsConstructedGenericMethod IsConstructedGenericMethod IsConstructedGenericMethod Inherited from MethodBase
IsConstructor IsConstructor IsConstructor IsConstructor

获取一个值,该值指示此方法是否为构造函数。Gets a value indicating whether the method is a constructor.

(Inherited from MethodBase)
IsFamily IsFamily IsFamily IsFamily

获取一个值,该值指示此方法或构造函数的可见性是否由 Family 描述;也就是说,此方法或构造函数仅在其类和派生类内可见。Gets a value indicating whether the visibility of this method or constructor is described by Family; that is, the method or constructor is visible only within its class and derived classes.

(Inherited from MethodBase)
IsFamilyAndAssembly IsFamilyAndAssembly IsFamilyAndAssembly IsFamilyAndAssembly

获取一个值,该值指示此方法或构造函数的可见性是否由 FamANDAssem 描述;也就是说,此方法或构造函数可由派生类调用,但仅当这些派生类在同一程序集中时。Gets a value indicating whether the visibility of this method or constructor is described by FamANDAssem; that is, the method or constructor can be called by derived classes, but only if they are in the same assembly.

(Inherited from MethodBase)
IsFamilyOrAssembly IsFamilyOrAssembly IsFamilyOrAssembly IsFamilyOrAssembly

获取一个值,该值指示此方法或构造函数的潜在可见性是否由 FamORAssem 描述;也就是说,此方法或构造函数可由派生类(无论其位置如何)和同一程序集中的类调用。Gets a value indicating whether the potential visibility of this method or constructor is described by FamORAssem; that is, the method or constructor can be called by derived classes wherever they are, and by classes in the same assembly.

(Inherited from MethodBase)
IsFinal IsFinal IsFinal IsFinal

获取一个值,该值指示此方法是否为 finalGets a value indicating whether this method is final.

(Inherited from MethodBase)
IsGenericMethod IsGenericMethod IsGenericMethod IsGenericMethod

获取一个值,该值指示当前方法是否为泛型方法。Gets a value indicating whether the current method is a generic method.

(Inherited from MethodInfo)
IsGenericMethodDefinition IsGenericMethodDefinition IsGenericMethodDefinition IsGenericMethodDefinition

获取一个值,该值指示当前 MethodInfo 是否表示泛型方法的定义。Gets a value indicating whether the current MethodInfo represents the definition of a generic method.

(Inherited from MethodInfo)
IsHideBySig IsHideBySig IsHideBySig IsHideBySig

获取一个值,该值指示是否只有一个签名完全相同的同一种类的成员在派生类中是隐藏的。Gets a value indicating whether only a member of the same kind with exactly the same signature is hidden in the derived class.

(Inherited from MethodBase)
IsPrivate IsPrivate IsPrivate IsPrivate

获取一个值,该值指示此成员是否是私有的。Gets a value indicating whether this member is private.

(Inherited from MethodBase)
IsPublic IsPublic IsPublic IsPublic

获取一个值,该值指示这是否是一个公共方法。Gets a value indicating whether this is a public method.

(Inherited from MethodBase)
IsSecurityCritical IsSecurityCritical IsSecurityCritical IsSecurityCritical

获取一个值,该值指示当前动态方法是安全关键的还是安全可靠关键的,因此可以执行关键操作。Gets a value that indicates whether the current dynamic method is security-critical or security-safe-critical, and therefore can perform critical operations.

IsSecuritySafeCritical IsSecuritySafeCritical IsSecuritySafeCritical IsSecuritySafeCritical

获取一个值,该值指示当前动态方法在当前信任级别上是否是安全可靠关键的;即它是否可以执行关键操作并可以由透明代码访问。Gets a value that indicates whether the current dynamic method is security-safe-critical at the current trust level; that is, whether it can perform critical operations and can be accessed by transparent code.

IsSecurityTransparent IsSecurityTransparent IsSecurityTransparent IsSecurityTransparent

获取一个值,该值指示动态方法在当前信任级别上是透明的,因此无法执行关键操作。Gets a value that indicates whether the current dynamic method is transparent at the current trust level, and therefore cannot perform critical operations.

IsSpecialName IsSpecialName IsSpecialName IsSpecialName

获取一个值,该值指示此方法是否具有特殊名称。Gets a value indicating whether this method has a special name.

(Inherited from MethodBase)
IsStatic IsStatic IsStatic IsStatic

获取一个值,该值指示方法是否为 staticGets a value indicating whether the method is static.

(Inherited from MethodBase)
IsVirtual IsVirtual IsVirtual IsVirtual

获取一个值,该值指示方法是否为 virtualGets a value indicating whether the method is virtual.

(Inherited from MethodBase)
MemberType MemberType MemberType MemberType

获取一个 MemberTypes 值,该值指示此成员是方法。Gets a MemberTypes value indicating that this member is a method.

(Inherited from MethodInfo)
MetadataToken MetadataToken MetadataToken MetadataToken

获取一个值,该值标识元数据元素。Gets a value that identifies a metadata element.

(Inherited from MemberInfo)
MethodHandle MethodHandle MethodHandle MethodHandle

动态方法不支持。Not supported for dynamic methods.

MethodImplementationFlags MethodImplementationFlags MethodImplementationFlags MethodImplementationFlags
Module Module Module Module

获取动态方法逻辑关联的模块。Gets the module with which the dynamic method is logically associated.

Name Name Name Name

获取动态方法的名称。Gets the name of the dynamic method.

ReflectedType ReflectedType ReflectedType ReflectedType

获取在反射中用于获取方法的类。Gets the class that was used in reflection to obtain the method.

ReturnParameter ReturnParameter ReturnParameter ReturnParameter

获取动态方法的返回参数。Gets the return parameter of the dynamic method.

ReturnType ReturnType ReturnType ReturnType

获取动态方法的返回值的类型。Gets the type of return value for the dynamic method.

ReturnTypeCustomAttributes ReturnTypeCustomAttributes ReturnTypeCustomAttributes ReturnTypeCustomAttributes

获取动态方法的返回类型的自定义属性。Gets the custom attributes of the return type for the dynamic method.

_MethodBase.IsAbstract _MethodBase.IsAbstract _MethodBase.IsAbstract _MethodBase.IsAbstract

有关此成员的说明,请参见 IsAbstractFor a description of this member, see IsAbstract.

(Inherited from MethodBase)
_MethodBase.IsAssembly _MethodBase.IsAssembly _MethodBase.IsAssembly _MethodBase.IsAssembly

有关此成员的说明,请参见 IsAssemblyFor a description of this member, see IsAssembly.

(Inherited from MethodBase)
_MethodBase.IsConstructor _MethodBase.IsConstructor _MethodBase.IsConstructor _MethodBase.IsConstructor

有关此成员的说明,请参见 IsConstructorFor a description of this member, see IsConstructor.

(Inherited from MethodBase)
_MethodBase.IsFamily _MethodBase.IsFamily _MethodBase.IsFamily _MethodBase.IsFamily

有关此成员的说明,请参见 IsFamilyFor a description of this member, see IsFamily.

(Inherited from MethodBase)
_MethodBase.IsFamilyAndAssembly _MethodBase.IsFamilyAndAssembly _MethodBase.IsFamilyAndAssembly _MethodBase.IsFamilyAndAssembly

有关此成员的说明,请参见 IsFamilyAndAssemblyFor a description of this member, see IsFamilyAndAssembly.

(Inherited from MethodBase)
_MethodBase.IsFamilyOrAssembly _MethodBase.IsFamilyOrAssembly _MethodBase.IsFamilyOrAssembly _MethodBase.IsFamilyOrAssembly

有关此成员的说明,请参见 IsFamilyOrAssemblyFor a description of this member, see IsFamilyOrAssembly.

(Inherited from MethodBase)
_MethodBase.IsFinal _MethodBase.IsFinal _MethodBase.IsFinal _MethodBase.IsFinal

有关此成员的说明,请参见 IsFinalFor a description of this member, see IsFinal.

(Inherited from MethodBase)
_MethodBase.IsHideBySig _MethodBase.IsHideBySig _MethodBase.IsHideBySig _MethodBase.IsHideBySig

有关此成员的说明,请参见 IsHideBySigFor a description of this member, see IsHideBySig.

(Inherited from MethodBase)
_MethodBase.IsPrivate _MethodBase.IsPrivate _MethodBase.IsPrivate _MethodBase.IsPrivate

有关此成员的说明,请参见 IsPrivateFor a description of this member, see IsPrivate.

(Inherited from MethodBase)
_MethodBase.IsPublic _MethodBase.IsPublic _MethodBase.IsPublic _MethodBase.IsPublic

有关此成员的说明,请参见 IsPublicFor a description of this member, see IsPublic.

(Inherited from MethodBase)
_MethodBase.IsSpecialName _MethodBase.IsSpecialName _MethodBase.IsSpecialName _MethodBase.IsSpecialName

有关此成员的说明,请参见 IsSpecialNameFor a description of this member, see IsSpecialName.

(Inherited from MethodBase)
_MethodBase.IsStatic _MethodBase.IsStatic _MethodBase.IsStatic _MethodBase.IsStatic

有关此成员的说明,请参见 IsStaticFor a description of this member, see IsStatic.

(Inherited from MethodBase)
_MethodBase.IsVirtual _MethodBase.IsVirtual _MethodBase.IsVirtual _MethodBase.IsVirtual

有关此成员的说明,请参见 IsVirtualFor a description of this member, see IsVirtual.

(Inherited from MethodBase)

方法

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

完成动态方法并创建一个可执行此方法的委托。Completes the dynamic method and creates a delegate that can be used to execute it.

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

完成动态方法并创建一个可用于执行该方法的委托,指定委托类型和委托绑定到的对象。Completes the dynamic method and creates a delegate that can be used to execute it, specifying the delegate type and an object the delegate is bound to.

DefineParameter(Int32, ParameterAttributes, String) DefineParameter(Int32, ParameterAttributes, String) DefineParameter(Int32, ParameterAttributes, String) DefineParameter(Int32, ParameterAttributes, String)

定义动态方法的参数。Defines a parameter of the dynamic method.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from MethodInfo)
GetBaseDefinition() GetBaseDefinition() GetBaseDefinition() GetBaseDefinition()

返回方法的基实现。Returns the base implementation for the method.

GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean)

返回为此方法定义的所有自定义属性。Returns all the custom attributes defined for the method.

GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean)

返回应用于此方法的指定类型的自定义属性。Returns the custom attributes of the specified type that have been applied to the method.

GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData()

返回 CustomAttributeData 对象列表,这些对象表示已应用到目标成员的特性相关数据。Returns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member.

(Inherited from MemberInfo)
GetDynamicILInfo() GetDynamicILInfo() GetDynamicILInfo() GetDynamicILInfo()

返回一个 DynamicILInfo 对象,该对象可用于从元数据标记、范围和 Microsoft 中间语言 (MSIL) 流生成方法体。Returns a DynamicILInfo object that can be used to generate a method body from metadata tokens, scopes, and Microsoft intermediate language (MSIL) streams.

GetGenericArguments() GetGenericArguments() GetGenericArguments() GetGenericArguments()

返回 Type 对象的数组,这些对象表示泛型方法的类型实参或泛型方法定义的类型形参。Returns an array of Type objects that represent the type arguments of a generic method or the type parameters of a generic method definition.

(Inherited from MethodInfo)
GetGenericMethodDefinition() GetGenericMethodDefinition() GetGenericMethodDefinition() GetGenericMethodDefinition()

返回一个 MethodInfo 对象,该对象表示可从其构造当前方法的泛型方法定义。Returns a MethodInfo object that represents a generic method definition from which the current method can be constructed.

(Inherited from MethodInfo)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

(Inherited from MethodInfo)
GetILGenerator() GetILGenerator() GetILGenerator() GetILGenerator()

为该方法返回一个具有默认 MSIL 流大小(64 字节)的 Microsoft 中间语言 (MSIL) 生成器。Returns a Microsoft intermediate language (MSIL) generator for the method with a default MSIL stream size of 64 bytes.

GetILGenerator(Int32) GetILGenerator(Int32) GetILGenerator(Int32) GetILGenerator(Int32)

为方法返回一个具有指定 MSIL 流大小的 Microsoft 中间语言 (MSIL) 生成器。Returns a Microsoft intermediate language (MSIL) generator for the method with the specified MSIL stream size.

GetMethodBody() GetMethodBody() GetMethodBody() GetMethodBody()

在派生类中重写后,获取 MethodBody 对象,该对象提供对 MSIL 流、局部变量和当前方法的异常的访问。When overridden in a derived class, gets a MethodBody object that provides access to the MSIL stream, local variables, and exceptions for the current method.

(Inherited from MethodBase)
GetMethodImplementationFlags() GetMethodImplementationFlags() GetMethodImplementationFlags() GetMethodImplementationFlags()

返回此方法的实现标志。Returns the implementation flags for the method.

GetParameters() GetParameters() GetParameters() GetParameters()

返回动态方法的参数。Returns the parameters of the dynamic method.

GetType() GetType() GetType() GetType() Inherited from MethodInfo
HasSameMetadataDefinitionAs(MemberInfo) HasSameMetadataDefinitionAs(MemberInfo) HasSameMetadataDefinitionAs(MemberInfo) HasSameMetadataDefinitionAs(MemberInfo) Inherited from MemberInfo
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) Invoke(Object, BindingFlags, Binder, Object[], CultureInfo) Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

使用指定的参数,在指定的联编程序的约束下,使用指定的区域性信息调用动态方法。Invokes the dynamic method using the specified parameters, under the constraints of the specified binder, with the specified culture information.

Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[]) Invoke(Object, Object[]) Inherited from MethodInfo
IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean)

指示是否定义了指定的自定义特性类型。Indicates whether the specified custom attribute type is defined.

MakeGenericMethod(Type[]) MakeGenericMethod(Type[]) MakeGenericMethod(Type[]) MakeGenericMethod(Type[])

用类型数组的元素替代当前泛型方法定义的类型参数,并返回表示结果构造方法的 MethodInfo 对象。Substitutes the elements of an array of types for the type parameters of the current generic method definition, and returns a MethodInfo object representing the resulting constructed method.

(Inherited from MethodInfo)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

返回方法的签名,以字符串表示。Returns the signature of the method, represented as a string.

显式界面实现

ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) Inherited from MemberInfo
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) Inherited from MemberInfo
ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) Inherited from MemberInfo
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from MemberInfo)
_MemberInfo.GetType() _MemberInfo.GetType() _MemberInfo.GetType() _MemberInfo.GetType()

获取一个表示 MemberInfo 类的 Type 对象。Gets a Type object representing the MemberInfo class.

(Inherited from MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can then be used to get the type information for an interface.

(Inherited from MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32) _MemberInfo.GetTypeInfoCount(UInt32) _MemberInfo.GetTypeInfoCount(UInt32) _MemberInfo.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from MethodBase)
_MethodBase.GetType() _MethodBase.GetType() _MethodBase.GetType() _MethodBase.GetType()

有关此成员的说明,请参见 GetType()For a description of this member, see GetType().

(Inherited from MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can then be used to get the type information for an interface.

(Inherited from MethodBase)
_MethodBase.GetTypeInfoCount(UInt32) _MethodBase.GetTypeInfoCount(UInt32) _MethodBase.GetTypeInfoCount(UInt32) _MethodBase.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from MethodBase)
_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from MethodInfo)
_MethodInfo.GetType() _MethodInfo.GetType() _MethodInfo.GetType() _MethodInfo.GetType()

提供从 COM 对 GetType() 方法的访问。Provides access to the GetType() method from COM.

(Inherited from MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr) _MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32) _MethodInfo.GetTypeInfoCount(UInt32) _MethodInfo.GetTypeInfoCount(UInt32) _MethodInfo.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对某一对象公开的属性和方法的访问。Provides access to properties and methods exposed by an object.

(Inherited from MethodInfo)

扩展方法

GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type)

检索应用于指定成员的指定类型的自定义特性。Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean)

检索应用于指定成员的指定类型的自定义特性,并可选择检查该成员的上级。Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttribute<T>(MemberInfo) GetCustomAttribute<T>(MemberInfo) GetCustomAttribute<T>(MemberInfo) GetCustomAttribute<T>(MemberInfo)

检索应用于指定成员的指定类型的自定义特性。Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean)

检索应用于指定成员的指定类型的自定义特性,并可选择检查该成员的上级。Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo)

检索应用于指定成员的自定义特性集合。Retrieves a collection of custom attributes that are applied to a specified member.

GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean)

检索应用于指定成员的自定义特性集合,并可选择检查该成员的上级。Retrieves a collection of custom attributes that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type)

检索应用于指定成员的指定类型的自定义特性集合。Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean)

检索应用于指定成员的指定类型的自定义特性集合,并可选择检查该成员的上级。Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes<T>(MemberInfo) GetCustomAttributes<T>(MemberInfo) GetCustomAttributes<T>(MemberInfo) GetCustomAttributes<T>(MemberInfo)

检索应用于指定成员的指定类型的自定义特性集合。Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean)

检索应用于指定成员的指定类型的自定义特性集合,并可选择检查该成员的上级。Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member.

IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type)

确定是否将指定类型的任何自定义属性应用于指定的成员。Indicates whether custom attributes of a specified type are applied to a specified member.

IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean)

指示一个指定类型的自定义特性是否应用于一个指定的数字,并选择性地应用于其的上级。Indicates whether custom attributes of a specified type are applied to a specified member, and, optionally, applied to its ancestors.

GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo)

获取给定成员的元数据令牌(如果可用)。Gets a metadata token for the given member, if available.

HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo)

返回表示元数据令牌是否可用于指定的成员的值。Returns a value that indicates whether a metadata token is available for the specified member.

GetBaseDefinition(MethodInfo) GetBaseDefinition(MethodInfo) GetBaseDefinition(MethodInfo) GetBaseDefinition(MethodInfo)
GetRuntimeBaseDefinition(MethodInfo) GetRuntimeBaseDefinition(MethodInfo) GetRuntimeBaseDefinition(MethodInfo) GetRuntimeBaseDefinition(MethodInfo)

检索表示在此方法最先声明的直接或间接类上的指定方法的对象。Retrieves an object that represents the specified method on the direct or indirect base class where the method was first declared.

适用于

另请参阅