MethodBuilder 类

定义

定义并表示动态类上的方法(或构造函数)。

public ref class MethodBuilder sealed : System::Reflection::MethodInfo, System::Runtime::InteropServices::_MethodBuilder
public ref class MethodBuilder sealed : System::Reflection::MethodInfo
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
public sealed class MethodBuilder : System.Reflection.MethodInfo, System.Runtime.InteropServices._MethodBuilder
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class MethodBuilder : System.Reflection.MethodInfo, System.Runtime.InteropServices._MethodBuilder
public sealed class MethodBuilder : System.Reflection.MethodInfo
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
type MethodBuilder = class
    inherit MethodInfo
    interface _MethodBuilder
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.None)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type MethodBuilder = class
    inherit MethodInfo
    interface _MethodBuilder
type MethodBuilder = class
    inherit MethodInfo
Public NotInheritable Class MethodBuilder
Inherits MethodInfo
Implements _MethodBuilder
Public NotInheritable Class MethodBuilder
Inherits MethodInfo
继承
属性
实现

示例

以下示例使用 MethodBuilder 类在动态类型中创建方法。


using System;
using System.Reflection;
using System.Reflection.Emit;

class DemoMethodBuilder
{
    public static void AddMethodDynamically (TypeBuilder myTypeBld,
                                             string mthdName,
                                             Type[] mthdParams,
                                             Type returnType,
                                             string mthdAction)
    {

        MethodBuilder myMthdBld = myTypeBld.DefineMethod(
                                             mthdName,
                                             MethodAttributes.Public |
                                             MethodAttributes.Static,
                                             returnType,
                                             mthdParams);

        ILGenerator ILout = myMthdBld.GetILGenerator();

        int numParams = mthdParams.Length;

        for (byte x=0; x < numParams; x++)
        {
            ILout.Emit(OpCodes.Ldarg_S, x);
        }

        if (numParams > 1)
        {
            for (int y=0; y<(numParams-1); y++)
            {
                switch (mthdAction)
                {
                    case "A": ILout.Emit(OpCodes.Add);
                              break;
                    case "M": ILout.Emit(OpCodes.Mul);
                              break;
                    default: ILout.Emit(OpCodes.Add);
                              break;
                }
            }
        }
        ILout.Emit(OpCodes.Ret);
    }

    public static void Main()
    {
        AppDomain myDomain = AppDomain.CurrentDomain;
        AssemblyName asmName = new AssemblyName();
        asmName.Name = "MyDynamicAsm";

        AssemblyBuilder myAsmBuilder = myDomain.DefineDynamicAssembly(
                                       asmName,
                                       AssemblyBuilderAccess.RunAndSave);

        ModuleBuilder myModule = myAsmBuilder.DefineDynamicModule("MyDynamicAsm",
                                                                  "MyDynamicAsm.dll");

        TypeBuilder myTypeBld = myModule.DefineType("MyDynamicType",
                                                    TypeAttributes.Public);

        // Get info from the user to build the method dynamically.
        Console.WriteLine("Let's build a simple method dynamically!");
        Console.WriteLine("Please enter a few numbers, separated by spaces.");
        string inputNums = Console.ReadLine();
        Console.Write("Do you want to [A]dd (default) or [M]ultiply these numbers? ");
        string myMthdAction = Console.ReadLine().ToUpper();
        Console.Write("Lastly, what do you want to name your new dynamic method? ");
        string myMthdName = Console.ReadLine();

        // Process inputNums into an array and create a corresponding Type array
        int index = 0;
        string[] inputNumsList = inputNums.Split();

        Type[] myMthdParams = new Type[inputNumsList.Length];
        object[] inputValsList = new object[inputNumsList.Length];

        foreach (string inputNum in inputNumsList)
        {
            inputValsList[index] = (object)Convert.ToInt32(inputNum);
                myMthdParams[index] = typeof(int);
                index++;
        }

        // Now, call the method building method with the parameters, passing the
        // TypeBuilder by reference.
        AddMethodDynamically(myTypeBld,
                             myMthdName,
                             myMthdParams,
                             typeof(int),
                             myMthdAction);

        Type myType = myTypeBld.CreateType();

        Console.WriteLine("---");
        Console.WriteLine("The result of {0} the inputted values is: {1}",
                          ((myMthdAction == "M") ? "multiplying" : "adding"),
                          myType.InvokeMember(myMthdName,
                          BindingFlags.InvokeMethod | BindingFlags.Public |
                          BindingFlags.Static,
                          null,
                          null,
                          inputValsList));
        Console.WriteLine("---");

        // Let's take a look at the method we created.
        // If you are interested in seeing the MSIL generated dynamically for the method
        // your program generated, change to the directory where you ran the compiled
        // code sample and type "ildasm MyDynamicAsm.dll" at the prompt. When the list
        // of manifest contents appears, click on "MyDynamicType" and then on the name of
        // of the method you provided during execution.

        myAsmBuilder.Save("MyDynamicAsm.dll");

        MethodInfo myMthdInfo = myType.GetMethod(myMthdName);
        Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString());
    }
}
Imports System.Reflection
Imports System.Reflection.Emit

Class DemoMethodBuilder
   
   Public Shared Sub AddMethodDynamically(ByVal myTypeBld As TypeBuilder, _
                                          ByVal mthdName As String, _
                                          ByVal mthdParams() As Type, _
                                          ByVal returnType As Type, _
                                          ByVal mthdAction As String)
      
      Dim myMthdBld As MethodBuilder = myTypeBld.DefineMethod(mthdName, _
                                       MethodAttributes.Public Or MethodAttributes.Static, _
                                       returnType, _
                                       mthdParams)
      
      Dim ILout As ILGenerator = myMthdBld.GetILGenerator()
      
      Dim numParams As Integer = mthdParams.Length
      
      Dim x As Byte
      For x = 0 To numParams - 1
         ILout.Emit(OpCodes.Ldarg_S, x)
      Next x
      
      If numParams > 1 Then
         Dim y As Integer
         For y = 0 To (numParams - 1) - 1
            Select Case mthdAction
               Case "A"
                  ILout.Emit(OpCodes.Add)
               Case "M"
                  ILout.Emit(OpCodes.Mul)
               Case Else
                  ILout.Emit(OpCodes.Add)
            End Select
         Next y
      End If
      ILout.Emit(OpCodes.Ret)
   End Sub 
    
   
   Public Shared Sub Main()
      
      Dim myDomain As AppDomain = AppDomain.CurrentDomain
      Dim asmName As New AssemblyName()
      asmName.Name = "MyDynamicAsm"
      
      Dim myAsmBuilder As AssemblyBuilder = myDomain.DefineDynamicAssembly(asmName, _
                                            AssemblyBuilderAccess.RunAndSave)
      
      Dim myModule As ModuleBuilder = myAsmBuilder.DefineDynamicModule("MyDynamicAsm", _
                                                                       "MyDynamicAsm.dll")
      
      Dim myTypeBld As TypeBuilder = myModule.DefineType("MyDynamicType", TypeAttributes.Public)
      
      ' Get info from the user to build the method dynamically.
      Console.WriteLine("Let's build a simple method dynamically!")
      Console.WriteLine("Please enter a few numbers, separated by spaces.")
      Dim inputNums As String = Console.ReadLine()
      Console.Write("Do you want to [A]dd (default) or [M]ultiply these numbers? ")
      Dim myMthdAction As String = Console.ReadLine().ToUpper()
      Console.Write("Lastly, what do you want to name your new dynamic method? ")
      Dim myMthdName As String = Console.ReadLine()
      
      ' Process inputNums into an array and create a corresponding Type array 
      Dim index As Integer = 0
      Dim inputNumsList As String() = inputNums.Split()
      
      Dim myMthdParams(inputNumsList.Length - 1) As Type
      Dim inputValsList(inputNumsList.Length - 1) As Object
      
      
      Dim inputNum As String
      For Each inputNum In  inputNumsList
         inputValsList(index) = CType(Convert.ToInt32(inputNum), Object)
         myMthdParams(index) = GetType(Integer)
         index += 1
      Next inputNum
      
      ' Now, call the method building method with the parameters, passing the 
      ' TypeBuilder by reference.
      AddMethodDynamically(myTypeBld, myMthdName, myMthdParams, GetType(Integer), myMthdAction)
      
      Dim myType As Type = myTypeBld.CreateType()
     
      Dim description as String 
      If myMthdAction = "M" Then
         description = "multiplying"
      Else
         description = "adding"
      End If

      Console.WriteLine("---")
      Console.WriteLine("The result of {0} the values is: {1}", _
                         description, _
                         myType.InvokeMember(myMthdName, _
                                             BindingFlags.InvokeMethod _
                                               Or BindingFlags.Public _
                                               Or BindingFlags.Static, _
                                             Nothing, _
                                             Nothing, _
                                             inputValsList)) 
      Console.WriteLine("---")

      ' If you are interested in seeing the MSIL generated dynamically for the method
      ' your program generated, change to the directory where you ran the compiled
      ' code sample and type "ildasm MyDynamicAsm.dll" at the prompt. When the list
      ' of manifest contents appears, click on "MyDynamicType" and then on the name of
      ' of the method you provided during execution.
 
      myAsmBuilder.Save("MyDynamicAsm.dll") 

      Dim myMthdInfo As MethodInfo = myType.GetMethod(myMthdName)
      Console.WriteLine("Your Dynamic Method: {0};", myMthdInfo.ToString())
   End Sub 
End Class

注解

有关此 API 的详细信息,请参阅 MethodBuilder 的补充 API 说明

属性

名称 说明
Attributes

检索此方法的属性。

CallingConvention

返回方法的调用约定。

ContainsGenericParameters

此类型不支持。

CustomAttributes

获取包含此成员的自定义属性的集合。

(继承自 MemberInfo)
DeclaringType

返回声明此方法的类型。

InitLocals

获取或设置一个布尔值,该值指定此方法中的局部变量是否初始化为零。 此属性的默认值为 true

IsAbstract

获取一个值,该值指示该方法是否为抽象方法。

(继承自 MethodBase)
IsAssembly

获取一个值,该值指示此方法或构造函数的潜在可见性是否由 Assembly该方法或构造函数描述;也就是说,该方法或构造函数对同一程序集中的其他类型最多可见,并且对程序集外部的派生类型不可见。

(继承自 MethodBase)
IsConstructedGenericMethod

定义并表示动态类上的方法(或构造函数)。

IsConstructor

获取一个值,该值指示该方法是否为构造函数。

(继承自 MethodBase)
IsFamily

获取一个值,该值指示此方法或构造函数的可见性是否由 Family该方法或构造函数描述;也就是说,该方法或构造函数仅在其类和派生类中可见。

(继承自 MethodBase)
IsFamilyAndAssembly

获取一个值,该值指示此方法或构造函数的可见性是否由 FamANDAssem;也就是说,方法或构造函数可由派生类调用,但前提是它们位于同一程序集中。

(继承自 MethodBase)
IsFamilyOrAssembly

获取一个值,该值指示此方法或构造函数的潜在可见性是否由 FamORAssem;也就是说,无论它们位于何处,都可以由派生类和同一程序集中的类调用该方法或构造函数。

(继承自 MethodBase)
IsFinal

获取一个值,该值指示此方法是否为 final

(继承自 MethodBase)
IsGenericMethod

获取一个值,该值指示该方法是否为泛型方法。

IsGenericMethodDefinition

获取一个值,该值指示当前 MethodBuilder 对象是否表示泛型方法的定义。

IsHideBySig

获取一个值,该值指示在派生类中是否仅隐藏具有相同签名的同一类型的成员。

(继承自 MethodBase)
IsPrivate

获取一个值,该值指示此成员是否为私有成员。

(继承自 MethodBase)
IsPublic

获取一个值,该值指示这是否为公共方法。

(继承自 MethodBase)
IsSecurityCritical

在所有情况下都引发一个 NotSupportedException

IsSecurityCritical

获取一个值,该值指示当前方法或构造函数在当前信任级别是安全关键型还是安全安全关键型,因此可以执行关键操作。

(继承自 MethodBase)
IsSecuritySafeCritical

在所有情况下都引发一个 NotSupportedException

IsSecuritySafeCritical

获取一个值,该值指示当前方法或构造函数在当前信任级别是安全安全关键;也就是说,它是否可以执行关键操作,并且可以通过透明代码访问。

(继承自 MethodBase)
IsSecurityTransparent

在所有情况下都引发一个 NotSupportedException

IsSecurityTransparent

获取一个值,该值指示当前方法或构造函数在当前信任级别是否透明,因此无法执行关键操作。

(继承自 MethodBase)
IsSpecialName

获取一个值,该值指示此方法是否具有特殊名称。

(继承自 MethodBase)
IsStatic

获取一个值,该值指示方法是否为 static

(继承自 MethodBase)
IsVirtual

获取一个值,该值指示方法是否为 virtual

(继承自 MethodBase)
MemberType

获取一个 MemberTypes 值,该值指示此成员是一个方法。

(继承自 MethodInfo)
MetadataToken

获取标识元数据元素的值。

(继承自 MemberInfo)
MethodHandle

检索方法的内部句柄。 使用此句柄访问基础元数据句柄。

MethodImplementationFlags

MethodImplAttributes获取指定方法实现的属性的标志。

(继承自 MethodBase)
Module

获取要在其中定义当前方法的模块。

Name

检索此方法的名称。

ReflectedType

检索反射中使用的类以获取此对象。

ReturnParameter

获取一个 ParameterInfo 对象,该对象包含有关方法的返回类型的信息,例如返回类型是否具有自定义修饰符。

ReturnType

获取由此 MethodBuilder表示的方法的返回类型。

ReturnType

获取此方法的返回类型。

(继承自 MethodInfo)
ReturnTypeCustomAttributes

返回方法的返回类型的自定义属性。

Signature

检索方法的签名。

方法

名称 说明
AddDeclarativeSecurity(SecurityAction, PermissionSet)

向此方法添加声明性安全性。

CreateDelegate(Type, Object)

使用此方法中的指定目标创建指定类型的委托。

(继承自 MethodInfo)
CreateDelegate(Type)

从此方法创建指定类型的委托。

(继承自 MethodInfo)
CreateMethodBody(Byte[], Int32)

使用提供的Microsoft中间语言(MSIL)指令的字节数组创建方法的正文。

DefineGenericParameters(String[])

设置当前方法的泛型类型参数数,指定其名称,并返回可用于定义其约束的对象数组 GenericTypeParameterBuilder

DefineParameter(Int32, ParameterAttributes, String)

设置参数属性和此方法的参数的名称,或此方法的返回值的名称。 返回可用于应用自定义属性的 ParameterBuilder。

Equals(Object)

确定给定对象是否等于此实例。

GetBaseDefinition()

返回方法的基实现。

GetCustomAttributes(Boolean)

返回为此方法定义的所有自定义属性。

GetCustomAttributes(Type, Boolean)

返回由给定类型标识的自定义属性。

GetCustomAttributesData()

返回一个对象列表,该列表 CustomAttributeData 表示已应用于目标成员的属性的相关数据。

(继承自 MemberInfo)
GetGenericArguments()

返回一个对象数组 GenericTypeParameterBuilder ,表示方法的类型参数(如果它是泛型)。

GetGenericMethodDefinition()

返回此方法。

GetHashCode()

获取此方法的哈希代码。

GetILGenerator()

为此方法返回一个 ILGenerator,此方法的默认Microsoft中间语言 (MSIL) 流大小为 64 字节。

GetILGenerator(Int32)

返回具有指定Microsoft中间语言 (MSIL) 流大小的此方法的 ILGenerator

GetMethodBody()

在派生类中重写时,获取一个 MethodBody 对象,该对象提供对当前方法的 MSIL 流、局部变量和异常的访问权限。

(继承自 MethodBase)
GetMethodImplementationFlags()

返回方法的实现标志。

GetModule()

返回对包含此方法的模块的引用。

GetParameters()

返回此方法的参数。

GetToken()

返回表示 MethodToken 此方法的标记。

GetType()

发现方法的属性,并提供对方法元数据的访问权限。

(继承自 MethodInfo)
HasSameMetadataDefinitionAs(MemberInfo)

定义并表示动态类上的方法(或构造函数)。

(继承自 MemberInfo)
Invoke(Object, BindingFlags, Binder, Object[], CultureInfo)

在给定对象上动态调用此实例反映的方法,沿指定参数传递,并受给定绑定器的约束。

Invoke(Object, Object[])

使用指定的参数调用由当前实例表示的方法或构造函数。

(继承自 MethodInfo)
IsDefined(Type, Boolean)

检查是否定义了指定的自定义属性类型。

MakeGenericMethod(Type[])

返回使用指定的泛型类型参数从当前泛型方法定义构造的泛型方法。

MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
SetCustomAttribute(ConstructorInfo, Byte[])

使用指定的自定义属性 blob 设置自定义属性。

SetCustomAttribute(CustomAttributeBuilder)

使用自定义属性生成器设置自定义属性。

SetImplementationFlags(MethodImplAttributes)

设置此方法的实现标志。

SetMarshal(UnmanagedMarshal)
已过时.

设置此方法的返回类型的封送信息。

SetMethodBody(Byte[], Int32, Byte[], IEnumerable<ExceptionHandler>, IEnumerable<Int32>)

使用Microsoft中间语言(MSIL)指令的指定字节数组创建方法的正文。

SetParameters(Type[])

设置方法的参数的数量和类型。

SetReturnType(Type)

设置方法的返回类型。

SetSignature(Type, Type[], Type[], Type[], Type[][], Type[][])

设置方法签名,包括返回类型、参数类型以及返回类型和参数类型的必需和可选的自定义修饰符。

SetSymCustomAttribute(String, Byte[])

使用 Blob 设置符号自定义属性。

ToString()

以字符串的形式返回此 MethodBuilder 实例。

显式接口实现

名称 说明
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

(继承自 MemberInfo)
_MemberInfo.GetType()

获取表示TypeMemberInfo类的对象。

(继承自 MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

(继承自 MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对对象公开的属性和方法的访问。

(继承自 MemberInfo)
_MethodBase.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

(继承自 MethodBase)
_MethodBase.GetType()

有关此成员的说明,请参阅 GetType()

(继承自 MethodBase)
_MethodBase.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

(继承自 MethodBase)
_MethodBase.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 MethodBase)
_MethodBase.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对对象公开的属性和方法的访问。

(继承自 MethodBase)
_MethodBase.IsAbstract

有关此成员的说明,请参阅 IsAbstract

(继承自 MethodBase)
_MethodBase.IsAssembly

有关此成员的说明,请参阅 IsAssembly

(继承自 MethodBase)
_MethodBase.IsConstructor

有关此成员的说明,请参阅 IsConstructor

(继承自 MethodBase)
_MethodBase.IsFamily

有关此成员的说明,请参阅 IsFamily

(继承自 MethodBase)
_MethodBase.IsFamilyAndAssembly

有关此成员的说明,请参阅 IsFamilyAndAssembly

(继承自 MethodBase)
_MethodBase.IsFamilyOrAssembly

有关此成员的说明,请参阅 IsFamilyOrAssembly

(继承自 MethodBase)
_MethodBase.IsFinal

有关此成员的说明,请参阅 IsFinal

(继承自 MethodBase)
_MethodBase.IsHideBySig

有关此成员的说明,请参阅 IsHideBySig

(继承自 MethodBase)
_MethodBase.IsPrivate

有关此成员的说明,请参阅 IsPrivate

(继承自 MethodBase)
_MethodBase.IsPublic

有关此成员的说明,请参阅 IsPublic

(继承自 MethodBase)
_MethodBase.IsSpecialName

有关此成员的说明,请参阅 IsSpecialName

(继承自 MethodBase)
_MethodBase.IsStatic

有关此成员的说明,请参阅 IsStatic

(继承自 MethodBase)
_MethodBase.IsVirtual

有关此成员的说明,请参阅 IsVirtual

(继承自 MethodBase)
_MethodBuilder.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

_MethodBuilder.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,然后可以使用该信息获取接口的类型信息。

_MethodBuilder.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

_MethodBuilder.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对对象公开的属性和方法的访问。

_MethodInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

将一组名称映射为对应的一组调度标识符。

(继承自 MethodInfo)
_MethodInfo.GetType()

提供从 COM 访问 GetType() 方法的访问权限。

(继承自 MethodInfo)
_MethodInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

检索对象的类型信息,该信息可用于获取接口的类型信息。

(继承自 MethodInfo)
_MethodInfo.GetTypeInfoCount(UInt32)

检索对象提供的类型信息接口的数量(0 或 1)。

(继承自 MethodInfo)
_MethodInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供对对象公开的属性和方法的访问。

(继承自 MethodInfo)

扩展方法

名称 说明
GetCustomAttribute(MemberInfo, Type, Boolean)

检索应用于指定成员的指定类型的自定义属性,并选择性地检查该成员的上级。

GetCustomAttribute(MemberInfo, Type)

检索应用于指定成员的指定类型的自定义属性。

GetCustomAttribute<T>(MemberInfo, Boolean)

检索应用于指定成员的指定类型的自定义属性,并选择性地检查该成员的上级。

GetCustomAttribute<T>(MemberInfo)

检索应用于指定成员的指定类型的自定义属性。

GetCustomAttributes(MemberInfo, Boolean)

检索应用于指定成员的自定义属性的集合,并选择性地检查该成员的上级。

GetCustomAttributes(MemberInfo, Type, Boolean)

检索应用于指定成员的指定类型的自定义属性集合,并选择性地检查该成员的上级。

GetCustomAttributes(MemberInfo, Type)

检索应用于指定成员的指定类型的自定义属性集合。

GetCustomAttributes(MemberInfo)

检索应用于指定成员的自定义属性的集合。

GetCustomAttributes<T>(MemberInfo, Boolean)

检索应用于指定成员的指定类型的自定义属性集合,并选择性地检查该成员的上级。

GetCustomAttributes<T>(MemberInfo)

检索应用于指定成员的指定类型的自定义属性集合。

GetRuntimeBaseDefinition(MethodInfo)

检索一个对象,该对象表示首次声明该方法的直接或间接基类上的指定方法。

IsDefined(MemberInfo, Type, Boolean)

指示指定类型的自定义属性是否应用于指定成员,以及(可选)应用于其上级。

IsDefined(MemberInfo, Type)

指示指定类型的自定义属性是否应用于指定成员。

适用于