TypeBuilder.DefineMethod TypeBuilder.DefineMethod TypeBuilder.DefineMethod TypeBuilder.DefineMethod Method

定义

向类型添加一个方法。Adds a method to the type.

重载

DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes)

向此类型添加新方法,使用指定的名称和方法属性。Adds a new method to the type, with the specified name and method attributes.

DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions)

将具有指定的名称、 方法属性和调用约定的新方法添加到此类型。Adds a new method to the type, with the specified name, method attributes, and calling convention.

DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[])

向此类型添加新方法,并指定方法的名称、 属性和签名。Adds a new method to the type, with the specified name, method attributes, and method signature.

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[])

使用指定的名称、方法属性、调用约定和方法签名向类型中添加新方法。Adds a new method to the type, with the specified name, method attributes, calling convention, and method signature.

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][])

使用指定名称、方法属性、调用约定、方法签名和自定义修饰符向类型中添加新方法。Adds a new method to the type, with the specified name, method attributes, calling convention, method signature, and custom modifiers.

DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes) DefineMethod(String, MethodAttributes)

向此类型添加新方法,使用指定的名称和方法属性。Adds a new method to the type, with the specified name and method attributes.

public:
 System::Reflection::Emit::MethodBuilder ^ DefineMethod(System::String ^ name, System::Reflection::MethodAttributes attributes);
public System.Reflection.Emit.MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes);
member this.DefineMethod : string * System.Reflection.MethodAttributes -> System.Reflection.Emit.MethodBuilder
Public Function DefineMethod (name As String, attributes As MethodAttributes) As MethodBuilder

参数

name
String String String String

方法的名称。The name of the method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

返回

表示新定义的方法的 MethodBuilderA MethodBuilder representing the newly defined method.

异常

name 的长度为零。The length of name is zero.

-or- 此方法的父类型是一个接口,并且此方法不是虚方法(Visual Basic 中为 Overridable)。The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

示例

下面的代码示例定义了一个名为DemoMethod的泛型方法,该方法的参数类型和返回类型由其泛型类型参数指定。The following code example defines a generic method named DemoMethod whose parameter type and return type are specified by its generic type parameters. 使用标准调用约定定义方法时不使用签名。The method is defined without a signature, using the standard calling convention. 方法用于创建DemoMethod泛型方法,并将新定义的类型参数用于签名和返回类型。 MethodBuilder.DefineGenericParametersThe MethodBuilder.DefineGenericParameters method is used to make DemoMethod a generic method, and the newly defined type parameters are then used for the signature and return type.

此代码示例是为DefineGenericParameters方法提供的一个更大示例的一部分。This code example is part of a larger example provided for the DefineGenericParameters method.

// Define a Shared, Public method with standard calling
// conventions. Do not specify the parameter types or the
// return type, because type parameters will be used for
// those types, and the type parameters have not been
// defined yet.
MethodBuilder^ sampleMethodBuilder =
    sampleTypeBuilder->DefineMethod("SampleMethod",
    MethodAttributes::Public | MethodAttributes::Static);
// Define a Shared, Public method with standard calling
// conventions. Do not specify the parameter types or the
// return type, because type parameters will be used for 
// those types, and the type parameters have not been
// defined yet.
MethodBuilder demoMethod = demoType.DefineMethod(
    "DemoMethod", 
    MethodAttributes.Public | MethodAttributes.Static
);
' Define a Shared, Public method with standard calling
' conventions. Do not specify the parameter types or the
' return type, because type parameters will be used for 
' those types, and the type parameters have not been
' defined yet.
Dim demoMethod As MethodBuilder = _
    demoType.DefineMethod("DemoMethod", _
        MethodAttributes.Public Or MethodAttributes.Static)
// Defining generic parameters for the method makes it a
// generic method. By convention, type parameters are
// single alphabetic characters. T and U are used here.
//
array<String^>^ genericTypeNames = {"T", "U"};
array<GenericTypeParameterBuilder^>^ genericTypes =
    sampleMethodBuilder->DefineGenericParameters(
    genericTypeNames);
// Defining generic parameters for the method makes it a
// generic method. By convention, type parameters are 
// single alphabetic characters. T and U are used here.
//
string[] typeParamNames = {"T", "U"};
GenericTypeParameterBuilder[] typeParameters = 
    demoMethod.DefineGenericParameters(typeParamNames);

// The second type parameter is constrained to be a 
// reference type.
typeParameters[1].SetGenericParameterAttributes( 
    GenericParameterAttributes.ReferenceTypeConstraint);
' Defining generic parameters for the method makes it a
' generic method. By convention, type parameters are 
' single alphabetic characters. T and U are used here.
'
Dim typeParamNames() As String = {"T", "U"}
Dim typeParameters() As GenericTypeParameterBuilder = _
    demoMethod.DefineGenericParameters(typeParamNames)

' The second type parameter is constrained to be a 
' reference type.
typeParameters(1).SetGenericParameterAttributes( _
    GenericParameterAttributes.ReferenceTypeConstraint)
// Set parameter types for the method. The method takes
// one parameter, and its type is specified by the first
// type parameter, T.
array<Type^>^ parameterTypes = {genericTypes[0]};
sampleMethodBuilder->SetParameters(parameterTypes);

// Set the return type for the method. The return type is
// specified by the second type parameter, U.
sampleMethodBuilder->SetReturnType(genericTypes[1]);
// Set parameter types for the method. The method takes
// one parameter, and its type is specified by the first
// type parameter, T.
Type[] parms = {typeParameters[0]};
demoMethod.SetParameters(parms);

// Set the return type for the method. The return type is
// specified by the second type parameter, U.
demoMethod.SetReturnType(typeParameters[1]);
' Set parameter types for the method. The method takes
' one parameter, and its type is specified by the first
' type parameter, T.
Dim params() As Type = {typeParameters(0)}
demoMethod.SetParameters(params)

' Set the return type for the method. The return type is
' specified by the second type parameter, U.
demoMethod.SetReturnType(typeParameters(1))

注解

如果在定义方法时不知道方法签名,请使用此方法重载。Use this method overload when you do not know the method signature at the time you define the method. 例如,泛型方法的参数类型和返回类型可能由方法的泛型类型参数指定,该方法必须在方法添加到类型后定义。For example, the parameter types and return type of a generic method might be specified by the method's generic type parameters, which must be defined after the method has been added to the type. 以后可以使用MethodBuilder.SetSignature方法设置方法的参数和返回类型。The parameters and return type of the method can be set later using the MethodBuilder.SetSignature method.

此方法重载使用CallingConventions.Standard定义方法。This method overload defines a method with CallingConventions.Standard. 如果需要使用不同的调用约定来定义不带签名的方法,请使用DefineMethod(String, MethodAttributes, CallingConventions)方法重载。If you need to define a method without a signature, with a different calling convention, use the DefineMethod(String, MethodAttributes, CallingConventions) method overload.

另请参阅

DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions) DefineMethod(String, MethodAttributes, CallingConventions)

将具有指定的名称、 方法属性和调用约定的新方法添加到此类型。Adds a new method to the type, with the specified name, method attributes, and calling convention.

public:
 System::Reflection::Emit::MethodBuilder ^ DefineMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention);
public System.Reflection.Emit.MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention);
member this.DefineMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions -> System.Reflection.Emit.MethodBuilder
Public Function DefineMethod (name As String, attributes As MethodAttributes, callingConvention As CallingConventions) As MethodBuilder

参数

name
String String String String

方法的名称。The name of the method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions CallingConventions

方法的调用约定。The calling convention of the method.

返回

表示新定义的方法的 MethodBuilderA MethodBuilder representing the newly defined method.

异常

name 的长度为零。The length of name is zero.

-or- 此方法的父类型是一个接口,并且此方法不是虚方法(Visual Basic 中为 Overridable)。The type of the parent of this method is an interface and this method is not virtual (Overridable in Visual Basic).

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

注解

如果在定义方法时不知道方法签名,请使用此方法重载。Use this method overload when you do not know the method signature at the time you define the method. 例如,泛型方法的参数类型和返回类型可能由方法的泛型类型参数指定,该方法必须在方法添加到类型后定义。For example, the parameter types and return type of a generic method might be specified by the method's generic type parameters, which must be defined after the method has been added to the type. 以后可以使用MethodBuilder.SetSignature方法设置方法的参数和返回类型。The parameters and return type of the method can be set later using the MethodBuilder.SetSignature method.

另请参阅

DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[]) DefineMethod(String, MethodAttributes, Type, Type[])

向此类型添加新方法,并指定方法的名称、 属性和签名。Adds a new method to the type, with the specified name, method attributes, and method signature.

public:
 System::Reflection::Emit::MethodBuilder ^ DefineMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
public System.Reflection.Emit.MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, Type returnType, Type[] parameterTypes);
member this.DefineMethod : string * System.Reflection.MethodAttributes * Type * Type[] -> System.Reflection.Emit.MethodBuilder
Public Function DefineMethod (name As String, attributes As MethodAttributes, returnType As Type, parameterTypes As Type()) As MethodBuilder

参数

name
String String String String

方法的名称。The name of the method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

returnType
Type Type Type Type

方法的返回类型。The return type of the method.

parameterTypes
Type[]

方法参数的类型。The types of the parameters of the method.

返回

已定义的方法。The defined method.

异常

name 的长度为零。The length of name is zero.

- 或 --or- 此方法的父类型是一个接口,并且此方法不是虚方法(Visual Basic 中为 Overridable)。The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

示例

下面的代码示例演示DefineMethod如何使用在动态类型上设置构造函数的特定签名和特性,以及如何为 MSIL 填充返回相应MethodBuilder的。The following code sample demonstrates the use of DefineMethod to set a constructor's particular signature and attributes on a dynamic type and to return a corresponding MethodBuilder for MSIL population.

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
public interface class IMyInterface
{
   String^ HelloMethod( String^ parameter );
};

public ref class EmittedClass
{
public:
   // Because this method calls Activator::CreateInstance, 
   // it requires full trust. 
   [System::Security::Permissions::PermissionSetAttribute
	(System::Security::Permissions::SecurityAction::Demand, Name = "FullTrust")]
   static void Main()
   {
      Type^ myNestedClassType = CreateCallee( Thread::GetDomain() );
      
      // Create an instance of 'MyNestedClass'.
      IMyInterface^ myInterface = dynamic_cast<IMyInterface^>(Activator::CreateInstance( myNestedClassType ));
      Console::WriteLine( myInterface->HelloMethod( "Bill" ) );
   }

private:

   // Create the callee transient dynamic assembly.
   static Type^ CreateCallee( AppDomain^ myAppDomain )
   {
      AssemblyName^ myAssemblyName = gcnew AssemblyName;
      myAssemblyName->Name = "EmittedClass";
      
      // Create the callee dynamic assembly.
      AssemblyBuilder^ myAssembly = myAppDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Run );
      
      // Create a dynamic module in the callee assembly.
      ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( "EmittedModule" );
      
      // Define a public class named "MyHelloWorld".
      TypeBuilder^ myHelloWorldType = myModule->DefineType( "MyHelloWorld", TypeAttributes::Public );
      
      // Define a public nested class named 'MyNestedClass'.
      array<Type^>^temp0 = {IMyInterface::typeid};
      TypeBuilder^ myNestedClassType = myHelloWorldType->DefineNestedType( "MyNestedClass", TypeAttributes::NestedPublic, EmittedClass::typeid, temp0 );
      
      // Implement 'IMyInterface' interface.
      myNestedClassType->AddInterfaceImplementation( IMyInterface::typeid );
      
      // Define 'HelloMethod' of 'IMyInterface'.
      array<Type^>^temp1 = {String::typeid};
      MethodBuilder^ myHelloMethod = myNestedClassType->DefineMethod( "HelloMethod", static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::Virtual), String::typeid, temp1 );
      
      // Generate IL for 'GetGreeting' method.
      ILGenerator^ myMethodIL = myHelloMethod->GetILGenerator();
      myMethodIL->Emit( OpCodes::Ldstr, "Hi! " );
      myMethodIL->Emit( OpCodes::Ldarg_1 );
      array<Type^>^temp2 = {String::typeid,String::typeid};
      MethodInfo^ infoMethod = String::typeid->GetMethod( "Concat", temp2 );
      myMethodIL->Emit( OpCodes::Call, infoMethod );
      myMethodIL->Emit( OpCodes::Ret );
      MethodInfo^ myHelloMethodInfo = IMyInterface::typeid->GetMethod( "HelloMethod" );
      
      // Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType->DefineMethodOverride( myHelloMethod, myHelloMethodInfo );
      
      // Create 'MyHelloWorld' type.
      Type^ myType = myHelloWorldType->CreateType();
      
      // Create 'MyNestedClass' type.
      return myNestedClassType->CreateType();
   }
};

int main()
{
   EmittedClass::Main();
}
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Permissions;

public interface IMyInterface
{
   String HelloMethod(String parameter);
}

public class Example
{
   [PermissionSetAttribute(SecurityAction.Demand, Name="FullTrust")]
   public static void Main()
   {
      Type myNestedClassType = CreateCallee(Thread.GetDomain());
      // Cretae an instance of 'MyNestedClass'.
      IMyInterface myInterface =
         (IMyInterface)Activator.CreateInstance(myNestedClassType);
      Console.WriteLine(myInterface.HelloMethod("Bill"));
   }

   // Create the callee transient dynamic assembly.
   private static Type CreateCallee(AppDomain myAppDomain)
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "Example";
      // Create the callee dynamic assembly.
      AssemblyBuilder myAssembly =
         myAppDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
      // Create a dynamic module in the callee assembly.
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
      // Define a public class named "MyHelloWorld".
      TypeBuilder myHelloWorldType =
         myModule.DefineType("MyHelloWorld", TypeAttributes.Public);
      // Define a public nested class named 'MyNestedClass'.
      TypeBuilder myNestedClassType =
         myHelloWorldType.DefineNestedType("MyNestedClass",
            TypeAttributes.NestedPublic, typeof(Example),
            new Type[]{typeof(IMyInterface)});
      // Implement 'IMyInterface' interface.
      myNestedClassType.AddInterfaceImplementation(typeof(IMyInterface));
      // Define 'HelloMethod' of 'IMyInterface'.
      MethodBuilder myHelloMethod =
         myNestedClassType.DefineMethod("HelloMethod",
            MethodAttributes.Public | MethodAttributes.Virtual,
            typeof(String), new Type[]{typeof(String)});
      // Generate IL for 'GetGreeting' method.
      ILGenerator myMethodIL = myHelloMethod.GetILGenerator();
      myMethodIL.Emit(OpCodes.Ldstr, "Hi! ");
      myMethodIL.Emit(OpCodes.Ldarg_1);
      MethodInfo infoMethod =
         typeof(String).GetMethod("Concat",new Type[]{typeof(string),typeof(string)});
      myMethodIL.Emit(OpCodes.Call, infoMethod);
      myMethodIL.Emit(OpCodes.Ret);

      MethodInfo myHelloMethodInfo =
         typeof(IMyInterface).GetMethod("HelloMethod");
      // Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType.DefineMethodOverride(myHelloMethod, myHelloMethodInfo);
      // Create 'MyHelloWorld' type.
      Type myType = myHelloWorldType.CreateType();
      // Create 'MyNestedClass' type.
      return myNestedClassType.CreateType();
   }
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Security.Permissions

Public Interface IMyInterface
   Function HelloMethod(parameter As String) As String
End Interface 'IMyInterface

Public Class Example
   <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
   Public Shared Sub Main()
      Dim myNestedClassType As Type = CreateCallee(Thread.GetDomain())
      ' Create an instance of 'MyNestedClass'.
      Dim myInterface As IMyInterface = _
            CType(Activator.CreateInstance(myNestedClassType), IMyInterface)
      Console.WriteLine(myInterface.HelloMethod("Bill"))
   End Sub

   ' Create the callee transient dynamic assembly.
   Private Shared Function CreateCallee(myAppDomain As AppDomain) As Type
      Dim myAssemblyName As New AssemblyName()
      myAssemblyName.Name = "Example"
      ' Create the callee dynamic assembly.
      Dim myAssembly As AssemblyBuilder = _
               myAppDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
      ' Create a dynamic module in the callee assembly.
      Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
      ' Define a public class named "MyHelloWorld".
      Dim myHelloWorldType As TypeBuilder = _
               myModule.DefineType("MyHelloWorld", TypeAttributes.Public)
      ' Define a public nested class named 'MyNestedClass'.
      Dim myNestedClassType As TypeBuilder = _
               myHelloWorldType.DefineNestedType("MyNestedClass", TypeAttributes.NestedPublic, _
               GetType(Example), New Type() {GetType(IMyInterface)})
      ' Implement 'IMyInterface' interface.
      myNestedClassType.AddInterfaceImplementation(GetType(IMyInterface))
      ' Define 'HelloMethod' of 'IMyInterface'.
      Dim myHelloMethod As MethodBuilder = _
               myNestedClassType.DefineMethod("HelloMethod", MethodAttributes.Public Or _
               MethodAttributes.Virtual, GetType(String), New Type() {GetType(String)})
      ' Generate IL for 'GetGreeting' method.
      Dim myMethodIL As ILGenerator = myHelloMethod.GetILGenerator()
      myMethodIL.Emit(OpCodes.Ldstr, "Hi! ")
      myMethodIL.Emit(OpCodes.Ldarg_1)
      Dim infoMethod As MethodInfo = _
               GetType(String).GetMethod("Concat", New Type() {GetType(String), GetType(String)})
      myMethodIL.Emit(OpCodes.Call, infoMethod)
      myMethodIL.Emit(OpCodes.Ret)

      Dim myHelloMethodInfo As MethodInfo = GetType(IMyInterface).GetMethod("HelloMethod")
      ' Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType.DefineMethodOverride(myHelloMethod, myHelloMethodInfo)
      ' Create 'MyHelloWorld' type.
      Dim myType As Type = myHelloWorldType.CreateType()
      ' Create 'MyNestedClass' type.
      Return myNestedClassType.CreateType()
   End Function 'CreateCallee
End Class 'Example

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[])

使用指定的名称、方法属性、调用约定和方法签名向类型中添加新方法。Adds a new method to the type, with the specified name, method attributes, calling convention, and method signature.

public:
 System::Reflection::Emit::MethodBuilder ^ DefineMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ parameterTypes);
public System.Reflection.Emit.MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] parameterTypes);
member this.DefineMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] -> System.Reflection.Emit.MethodBuilder
Public Function DefineMethod (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, parameterTypes As Type()) As MethodBuilder

参数

name
String String String String

方法的名称。The name of the method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions CallingConventions

方法的调用约定。The calling convention of the method.

returnType
Type Type Type Type

方法的返回类型。The return type of the method.

parameterTypes
Type[]

方法参数的类型。The types of the parameters of the method.

返回

表示新定义的方法的 MethodBuilderA MethodBuilder representing the newly defined method.

异常

name 的长度为零。The length of name is zero.

- 或 --or- 此方法的父类型是一个接口,并且此方法不是虚方法(Visual Basic 中为 Overridable)。The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

示例

下面的代码示例演示DefineMethod如何使用在动态类型上设置构造函数的特定签名和特性,以及如何为 MSIL 填充返回相应MethodBuilder的。The following code sample demonstrates the use of DefineMethod to set a constructor's particular signature and attributes on a dynamic type and to return a corresponding MethodBuilder for MSIL population.

using namespace System;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
public interface class IMyInterface
{
   String^ HelloMethod( String^ parameter );
};

public ref class EmittedClass
{
public:
   // Because this method calls Activator::CreateInstance, 
   // it requires full trust. 
   [System::Security::Permissions::PermissionSetAttribute
	(System::Security::Permissions::SecurityAction::Demand, Name = "FullTrust")]
   static void Main()
   {
      Type^ myNestedClassType = CreateCallee( Thread::GetDomain() );
      
      // Create an instance of 'MyNestedClass'.
      IMyInterface^ myInterface = dynamic_cast<IMyInterface^>(Activator::CreateInstance( myNestedClassType ));
      Console::WriteLine( myInterface->HelloMethod( "Bill" ) );
   }

private:

   // Create the callee transient dynamic assembly.
   static Type^ CreateCallee( AppDomain^ myAppDomain )
   {
      AssemblyName^ myAssemblyName = gcnew AssemblyName;
      myAssemblyName->Name = "EmittedClass";
      
      // Create the callee dynamic assembly.
      AssemblyBuilder^ myAssembly = myAppDomain->DefineDynamicAssembly( myAssemblyName, AssemblyBuilderAccess::Run );
      
      // Create a dynamic module in the callee assembly.
      ModuleBuilder^ myModule = myAssembly->DefineDynamicModule( "EmittedModule" );
      
      // Define a public class named "MyHelloWorld".
      TypeBuilder^ myHelloWorldType = myModule->DefineType( "MyHelloWorld", TypeAttributes::Public );
      
      // Define a public nested class named 'MyNestedClass'.
      array<Type^>^temp0 = {IMyInterface::typeid};
      TypeBuilder^ myNestedClassType = myHelloWorldType->DefineNestedType( "MyNestedClass", TypeAttributes::NestedPublic, EmittedClass::typeid, temp0 );
      
      // Implement 'IMyInterface' interface.
      myNestedClassType->AddInterfaceImplementation( IMyInterface::typeid );
      
      // Define 'HelloMethod' of 'IMyInterface'.
      array<Type^>^temp1 = {String::typeid};
      MethodBuilder^ myHelloMethod = myNestedClassType->DefineMethod( "HelloMethod", static_cast<MethodAttributes>(MethodAttributes::Public | MethodAttributes::Virtual), String::typeid, temp1 );
      
      // Generate IL for 'GetGreeting' method.
      ILGenerator^ myMethodIL = myHelloMethod->GetILGenerator();
      myMethodIL->Emit( OpCodes::Ldstr, "Hi! " );
      myMethodIL->Emit( OpCodes::Ldarg_1 );
      array<Type^>^temp2 = {String::typeid,String::typeid};
      MethodInfo^ infoMethod = String::typeid->GetMethod( "Concat", temp2 );
      myMethodIL->Emit( OpCodes::Call, infoMethod );
      myMethodIL->Emit( OpCodes::Ret );
      MethodInfo^ myHelloMethodInfo = IMyInterface::typeid->GetMethod( "HelloMethod" );
      
      // Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType->DefineMethodOverride( myHelloMethod, myHelloMethodInfo );
      
      // Create 'MyHelloWorld' type.
      Type^ myType = myHelloWorldType->CreateType();
      
      // Create 'MyNestedClass' type.
      return myNestedClassType->CreateType();
   }
};

int main()
{
   EmittedClass::Main();
}
using System;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Security.Permissions;

public interface IMyInterface
{
   String HelloMethod(String parameter);
}

public class Example
{
   [PermissionSetAttribute(SecurityAction.Demand, Name="FullTrust")]
   public static void Main()
   {
      Type myNestedClassType = CreateCallee(Thread.GetDomain());
      // Cretae an instance of 'MyNestedClass'.
      IMyInterface myInterface =
         (IMyInterface)Activator.CreateInstance(myNestedClassType);
      Console.WriteLine(myInterface.HelloMethod("Bill"));
   }

   // Create the callee transient dynamic assembly.
   private static Type CreateCallee(AppDomain myAppDomain)
   {
      AssemblyName myAssemblyName = new AssemblyName();
      myAssemblyName.Name = "Example";
      // Create the callee dynamic assembly.
      AssemblyBuilder myAssembly =
         myAppDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
      // Create a dynamic module in the callee assembly.
      ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
      // Define a public class named "MyHelloWorld".
      TypeBuilder myHelloWorldType =
         myModule.DefineType("MyHelloWorld", TypeAttributes.Public);
      // Define a public nested class named 'MyNestedClass'.
      TypeBuilder myNestedClassType =
         myHelloWorldType.DefineNestedType("MyNestedClass",
            TypeAttributes.NestedPublic, typeof(Example),
            new Type[]{typeof(IMyInterface)});
      // Implement 'IMyInterface' interface.
      myNestedClassType.AddInterfaceImplementation(typeof(IMyInterface));
      // Define 'HelloMethod' of 'IMyInterface'.
      MethodBuilder myHelloMethod =
         myNestedClassType.DefineMethod("HelloMethod",
            MethodAttributes.Public | MethodAttributes.Virtual,
            typeof(String), new Type[]{typeof(String)});
      // Generate IL for 'GetGreeting' method.
      ILGenerator myMethodIL = myHelloMethod.GetILGenerator();
      myMethodIL.Emit(OpCodes.Ldstr, "Hi! ");
      myMethodIL.Emit(OpCodes.Ldarg_1);
      MethodInfo infoMethod =
         typeof(String).GetMethod("Concat",new Type[]{typeof(string),typeof(string)});
      myMethodIL.Emit(OpCodes.Call, infoMethod);
      myMethodIL.Emit(OpCodes.Ret);

      MethodInfo myHelloMethodInfo =
         typeof(IMyInterface).GetMethod("HelloMethod");
      // Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType.DefineMethodOverride(myHelloMethod, myHelloMethodInfo);
      // Create 'MyHelloWorld' type.
      Type myType = myHelloWorldType.CreateType();
      // Create 'MyNestedClass' type.
      return myNestedClassType.CreateType();
   }
}
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Security.Permissions

Public Interface IMyInterface
   Function HelloMethod(parameter As String) As String
End Interface 'IMyInterface

Public Class Example
   <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
   Public Shared Sub Main()
      Dim myNestedClassType As Type = CreateCallee(Thread.GetDomain())
      ' Create an instance of 'MyNestedClass'.
      Dim myInterface As IMyInterface = _
            CType(Activator.CreateInstance(myNestedClassType), IMyInterface)
      Console.WriteLine(myInterface.HelloMethod("Bill"))
   End Sub

   ' Create the callee transient dynamic assembly.
   Private Shared Function CreateCallee(myAppDomain As AppDomain) As Type
      Dim myAssemblyName As New AssemblyName()
      myAssemblyName.Name = "Example"
      ' Create the callee dynamic assembly.
      Dim myAssembly As AssemblyBuilder = _
               myAppDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run)
      ' Create a dynamic module in the callee assembly.
      Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule("EmittedModule")
      ' Define a public class named "MyHelloWorld".
      Dim myHelloWorldType As TypeBuilder = _
               myModule.DefineType("MyHelloWorld", TypeAttributes.Public)
      ' Define a public nested class named 'MyNestedClass'.
      Dim myNestedClassType As TypeBuilder = _
               myHelloWorldType.DefineNestedType("MyNestedClass", TypeAttributes.NestedPublic, _
               GetType(Example), New Type() {GetType(IMyInterface)})
      ' Implement 'IMyInterface' interface.
      myNestedClassType.AddInterfaceImplementation(GetType(IMyInterface))
      ' Define 'HelloMethod' of 'IMyInterface'.
      Dim myHelloMethod As MethodBuilder = _
               myNestedClassType.DefineMethod("HelloMethod", MethodAttributes.Public Or _
               MethodAttributes.Virtual, GetType(String), New Type() {GetType(String)})
      ' Generate IL for 'GetGreeting' method.
      Dim myMethodIL As ILGenerator = myHelloMethod.GetILGenerator()
      myMethodIL.Emit(OpCodes.Ldstr, "Hi! ")
      myMethodIL.Emit(OpCodes.Ldarg_1)
      Dim infoMethod As MethodInfo = _
               GetType(String).GetMethod("Concat", New Type() {GetType(String), GetType(String)})
      myMethodIL.Emit(OpCodes.Call, infoMethod)
      myMethodIL.Emit(OpCodes.Ret)

      Dim myHelloMethodInfo As MethodInfo = GetType(IMyInterface).GetMethod("HelloMethod")
      ' Implement 'HelloMethod' of 'IMyInterface'.
      myNestedClassType.DefineMethodOverride(myHelloMethod, myHelloMethodInfo)
      ' Create 'MyHelloWorld' type.
      Dim myType As Type = myHelloWorldType.CreateType()
      ' Create 'MyNestedClass' type.
      Return myNestedClassType.CreateType()
   End Function 'CreateCallee
End Class 'Example

DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][]) DefineMethod(String, MethodAttributes, CallingConventions, Type, Type[], Type[], Type[], Type[][], Type[][])

使用指定名称、方法属性、调用约定、方法签名和自定义修饰符向类型中添加新方法。Adds a new method to the type, with the specified name, method attributes, calling convention, method signature, and custom modifiers.

public:
 System::Reflection::Emit::MethodBuilder ^ DefineMethod(System::String ^ name, System::Reflection::MethodAttributes attributes, System::Reflection::CallingConventions callingConvention, Type ^ returnType, cli::array <Type ^> ^ returnTypeRequiredCustomModifiers, cli::array <Type ^> ^ returnTypeOptionalCustomModifiers, cli::array <Type ^> ^ parameterTypes, cli::array <cli::array <Type ^> ^> ^ parameterTypeRequiredCustomModifiers, cli::array <cli::array <Type ^> ^> ^ parameterTypeOptionalCustomModifiers);
public System.Reflection.Emit.MethodBuilder DefineMethod (string name, System.Reflection.MethodAttributes attributes, System.Reflection.CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers);
member this.DefineMethod : string * System.Reflection.MethodAttributes * System.Reflection.CallingConventions * Type * Type[] * Type[] * Type[] * Type[][] * Type[][] -> System.Reflection.Emit.MethodBuilder
Public Function DefineMethod (name As String, attributes As MethodAttributes, callingConvention As CallingConventions, returnType As Type, returnTypeRequiredCustomModifiers As Type(), returnTypeOptionalCustomModifiers As Type(), parameterTypes As Type(), parameterTypeRequiredCustomModifiers As Type()(), parameterTypeOptionalCustomModifiers As Type()()) As MethodBuilder

参数

name
String String String String

方法的名称。The name of the method. name 不能包含嵌入的 null。name cannot contain embedded nulls.

attributes
MethodAttributes MethodAttributes MethodAttributes MethodAttributes

方法的属性。The attributes of the method.

callingConvention
CallingConventions CallingConventions CallingConventions CallingConventions

方法的调用约定。The calling convention of the method.

returnType
Type Type Type Type

方法的返回类型。The return type of the method.

returnTypeRequiredCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型所必需的自定义修饰符,如 IsConstAn array of types representing the required custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有所需的自定义修饰符,则指定 nullIf the return type has no required custom modifiers, specify null.

returnTypeOptionalCustomModifiers
Type[]

一个类型数组,表示该方法的返回类型的可选自定义修饰符,如 IsConstAn array of types representing the optional custom modifiers, such as IsConst, for the return type of the method. 如果返回类型没有可选的自定义修饰符,则指定 nullIf the return type has no optional custom modifiers, specify null.

parameterTypes
Type[]

方法参数的类型。The types of the parameters of the method.

parameterTypeRequiredCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数所必需的自定义修饰符,如 IsConstEach array of types represents the required custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有所需的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no required custom modifiers, specify null instead of an array of types. 如果所有参数都没有所需的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have required custom modifiers, specify null instead of an array of arrays.

parameterTypeOptionalCustomModifiers
Type[][]

由类型数组组成的数组。An array of arrays of types. 每个类型数组均表示相应参数的可选自定义修饰符,如 IsConstEach array of types represents the optional custom modifiers for the corresponding parameter, such as IsConst. 如果某个特定参数没有可选的自定义修饰符,则指定 null,而不要指定类型数组。If a particular parameter has no optional custom modifiers, specify null instead of an array of types. 如果所有参数都没有可选的自定义修饰符,则指定 null,而不要指定由数组组成的数组。If none of the parameters have optional custom modifiers, specify null instead of an array of arrays.

返回

一个表示新添加方法的 MethodBuilder 对象。A MethodBuilder object representing the newly added method.

异常

name 的长度为零。The length of name is zero.

-or- 此方法的父类型是一个接口,并且此方法不是虚方法(Visual Basic 中为 Overridable)。The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

-or- parameterTypeRequiredCustomModifiersparameterTypeOptionalCustomModifiers 的大小与 parameterTypes 的大小不相等。The size of parameterTypeRequiredCustomModifiers or parameterTypeOptionalCustomModifiers does not equal the size of parameterTypes.

该类型是以前使用 CreateType() 创建的。The type was previously created using CreateType().

-or- 对于当前的动态类型,属性 IsGenericType 的值为 true,但属性 IsGenericTypeDefinition 的值为 falseFor the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

注解

如果需要指定自定义修饰符,请使用此重载。Use this overload if you need to specify custom modifiers. 如果在创建方法之后需要指定自定义修饰符,例如,对于其参数类型由其泛型类型参数指定的泛型方法,你可以使用DefineMethod(String, MethodAttributes)DefineMethod(String, MethodAttributes, CallingConventions)方法重载来定义方法,然后使用MethodBuilder.SetSignature方法定义具有自定义修饰符的参数和返回类型。If you need to specify custom modifiers after the method has been created, as you would, for example, with a generic method whose parameter types are specified by its generic type parameters, you can use the DefineMethod(String, MethodAttributes) or DefineMethod(String, MethodAttributes, CallingConventions) method overloads to define the method and then use the MethodBuilder.SetSignature method to define the parameter and return types with custom modifiers.

备注

有关自定义修饰符的详细信息,请参阅 ECMA Partition II 元数据文档。For more information on custom modifiers, see the ECMA Partition II Metadata documentation. 可联机获取该文档;请参阅 MSDN 上的 ECMA C# 和公共语言基础结构标准和 Ecma International 网站上的标准 ECMA-335 - 公共语言基础结构 (CLI)The documentation is available online; see ECMA C# and Common Language Infrastructure Standards on MSDN and Standard ECMA-335 - Common Language Infrastructure (CLI) on the Ecma International Web site.

适用于