TypeBuilder.DefineMethod Método

Definição

Adiciona um método ao tipo.Adds a method to the type.

Sobrecargas

DefineMethod(String, MethodAttributes)

Adiciona um novo método ao tipo, com o nome e os atributos de método especificados.Adds a new method to the type, with the specified name and method attributes.

DefineMethod(String, MethodAttributes, CallingConventions)

Adiciona um novo método ao tipo, com o nome, os atributos de método e a convenção de chamada especificados.Adds a new method to the type, with the specified name, method attributes, and calling convention.

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

Adiciona um novo método ao tipo, com o nome, os atributos de método e a assinatura de método especificados.Adds a new method to the type, with the specified name, method attributes, and method signature.

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

Adiciona um novo método ao tipo, com o nome, atributos de método, convenção de chamada e assinatura de método especificados.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[][])

Adiciona um novo método ao tipo, com o nome, os atributos de método, a convenção de chamada, a assinatura de método e os modificadores personalizados especificados.Adds a new method to the type, with the specified name, method attributes, calling convention, method signature, and custom modifiers.

DefineMethod(String, MethodAttributes)

Adiciona um novo método ao tipo, com o nome e os atributos de método especificados.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

Parâmetros

name
String

O nome do método.The name of the method. name não pode conter nulos inseridos.name cannot contain embedded nulls.

attributes
MethodAttributes

Os atributos do método.The attributes of the method.

Retornos

MethodBuilder

Um MethodBuilder representando o método recém-definido.A MethodBuilder representing the newly defined method.

Exceções

O comprimento de name é zero.The length of name is zero.

- ou --or- O tipo de pai desse método é uma interface e esse método não é virtual (Overridable no Visual Basic).The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

name é null.name is null.

O tipo foi criado anteriormente usando CreateType().The type was previously created using CreateType().

- ou --or- Para o tipo dinâmico atual, a propriedade IsGenericType é true, mas a propriedade IsGenericTypeDefinition é false.For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Exemplos

O exemplo de código a seguir define um método genérico chamado DemoMethod cujo tipo de parâmetro e tipo de retorno são especificados por seus parâmetros de tipo genérico.The following code example defines a generic method named DemoMethod whose parameter type and return type are specified by its generic type parameters. O método é definido sem uma assinatura, usando a Convenção de chamada padrão.The method is defined without a signature, using the standard calling convention. O MethodBuilder.DefineGenericParameters método é usado para criar DemoMethod um método genérico e os parâmetros de tipo recém-definido são usados para a assinatura e o tipo de retorno.The 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.

Este exemplo de código faz parte de um exemplo maior fornecido para o DefineGenericParameters método.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))

Comentários

Use essa sobrecarga de método quando você não souber a assinatura do método no momento em que definir o método.Use this method overload when you do not know the method signature at the time you define the method. Por exemplo, os tipos de parâmetro e o tipo de retorno de um método genérico podem ser especificados pelos parâmetros de tipo genérico do método, que devem ser definidos depois que o método tiver sido adicionado ao tipo.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. Os parâmetros e o tipo de retorno do método podem ser definidos mais tarde usando o MethodBuilder.SetSignature método.The parameters and return type of the method can be set later using the MethodBuilder.SetSignature method.

Essa sobrecarga de método define um método com CallingConventions.Standard .This method overload defines a method with CallingConventions.Standard. Se você precisar definir um método sem uma assinatura, com uma Convenção de chamada diferente, use a DefineMethod(String, MethodAttributes, CallingConventions) sobrecarga do método.If you need to define a method without a signature, with a different calling convention, use the DefineMethod(String, MethodAttributes, CallingConventions) method overload.

Confira também

Aplica-se a

DefineMethod(String, MethodAttributes, CallingConventions)

Adiciona um novo método ao tipo, com o nome, os atributos de método e a convenção de chamada especificados.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

Parâmetros

name
String

O nome do método.The name of the method. name não pode conter nulos inseridos.name cannot contain embedded nulls.

attributes
MethodAttributes

Os atributos do método.The attributes of the method.

callingConvention
CallingConventions

A convenção de chamada do método.The calling convention of the method.

Retornos

MethodBuilder

Um MethodBuilder representando o método recém-definido.A MethodBuilder representing the newly defined method.

Exceções

O comprimento de name é zero.The length of name is zero.

- ou --or- O tipo de pai desse método é uma interface e esse método não é virtual (Overridable no Visual Basic).The type of the parent of this method is an interface and this method is not virtual (Overridable in Visual Basic).

name é null.name is null.

O tipo foi criado anteriormente usando CreateType().The type was previously created using CreateType().

- ou --or- Para o tipo dinâmico atual, a propriedade IsGenericType é true, mas a propriedade IsGenericTypeDefinition é false.For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Comentários

Use essa sobrecarga de método quando você não souber a assinatura do método no momento em que definir o método.Use this method overload when you do not know the method signature at the time you define the method. Por exemplo, os tipos de parâmetro e o tipo de retorno de um método genérico podem ser especificados pelos parâmetros de tipo genérico do método, que devem ser definidos depois que o método tiver sido adicionado ao tipo.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. Os parâmetros e o tipo de retorno do método podem ser definidos mais tarde usando o MethodBuilder.SetSignature método.The parameters and return type of the method can be set later using the MethodBuilder.SetSignature method.

Confira também

Aplica-se a

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

Adiciona um novo método ao tipo, com o nome, os atributos de método e a assinatura de método especificados.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);
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

Parâmetros

name
String

O nome do método.The name of the method. name não pode conter nulos inseridos.name cannot contain embedded nulls.

attributes
MethodAttributes

Os atributos do método.The attributes of the method.

returnType
Type

O tipo de retorno do método.The return type of the method.

parameterTypes
Type[]

Os tipos dos parâmetros do método.The types of the parameters of the method.

Retornos

MethodBuilder

O método definido.The defined method.

Exceções

O comprimento de name é zero.The length of name is zero.

- ou --or- O tipo de pai desse método é uma interface e esse método não é virtual (Overridable no Visual Basic).The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

name é null.name is null.

O tipo foi criado anteriormente usando CreateType().The type was previously created using CreateType().

- ou --or- Para o tipo dinâmico atual, a propriedade IsGenericType é true, mas a propriedade IsGenericTypeDefinition é false.For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Exemplos

O exemplo de código a seguir demonstra o uso de DefineMethod para definir a assinatura e os atributos específicos de um construtor em um tipo dinâmico e retornar um correspondente MethodBuilder para população MSIL.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

Aplica-se a

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

Adiciona um novo método ao tipo, com o nome, atributos de método, convenção de chamada e assinatura de método especificados.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);
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

Parâmetros

name
String

O nome do método.The name of the method. name não pode conter nulos inseridos.name cannot contain embedded nulls.

attributes
MethodAttributes

Os atributos do método.The attributes of the method.

callingConvention
CallingConventions

A convenção de chamada do método.The calling convention of the method.

returnType
Type

O tipo de retorno do método.The return type of the method.

parameterTypes
Type[]

Os tipos dos parâmetros do método.The types of the parameters of the method.

Retornos

MethodBuilder

Um MethodBuilder representando o método recém-definido.A MethodBuilder representing the newly defined method.

Exceções

O comprimento de name é zero.The length of name is zero.

- ou --or- O tipo de pai desse método é uma interface e esse método não é virtual (Overridable no Visual Basic).The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

name é null.name is null.

O tipo foi criado anteriormente usando CreateType().The type was previously created using CreateType().

- ou --or- Para o tipo dinâmico atual, a propriedade IsGenericType é true, mas a propriedade IsGenericTypeDefinition é false.For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Exemplos

O exemplo de código a seguir demonstra o uso de DefineMethod para definir a assinatura e os atributos específicos de um construtor em um tipo dinâmico e retornar um correspondente MethodBuilder para população MSIL.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

Aplica-se a

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

Adiciona um novo método ao tipo, com o nome, os atributos de método, a convenção de chamada, a assinatura de método e os modificadores personalizados especificados.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);
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

Parâmetros

name
String

O nome do método.The name of the method. name não pode conter nulos inseridos.name cannot contain embedded nulls.

attributes
MethodAttributes

Os atributos do método.The attributes of the method.

callingConvention
CallingConventions

A convenção de chamada do método.The calling convention of the method.

returnType
Type

O tipo de retorno do método.The return type of the method.

returnTypeRequiredCustomModifiers
Type[]

Uma matriz de tipos que representam os modificadores personalizados obrigatórios, por exemplo IsConst, para o tipo de retorno do método.An array of types representing the required custom modifiers, such as IsConst, for the return type of the method. Se o tipo de retorno não tiver modificadores personalizados obrigatórios, especifique null.If the return type has no required custom modifiers, specify null.

returnTypeOptionalCustomModifiers
Type[]

Uma matriz de tipos que representam os modificadores personalizados opcionais, por exemplo IsConst, para o tipo de retorno do método.An array of types representing the optional custom modifiers, such as IsConst, for the return type of the method. Se o tipo de retorno não tiver modificadores personalizados opcionais, especifique null.If the return type has no optional custom modifiers, specify null.

parameterTypes
Type[]

Os tipos dos parâmetros do método.The types of the parameters of the method.

parameterTypeRequiredCustomModifiers
Type[][]

Uma matriz de matrizes de tipos.An array of arrays of types. Cada matriz de tipos representa os modificadores personalizados obrigatórios para o parâmetro correspondente, por exemplo IsConst.Each array of types represents the required custom modifiers for the corresponding parameter, such as IsConst. Se um determinado parâmetro tiver não modificadores personalizados obrigatórios, especifique null em vez de uma matriz de tipos.If a particular parameter has no required custom modifiers, specify null instead of an array of types. Se nenhum dos parâmetros tiver modificadores personalizados obrigatórios, especifique null em vez de uma matriz de matrizes.If none of the parameters have required custom modifiers, specify null instead of an array of arrays.

parameterTypeOptionalCustomModifiers
Type[][]

Uma matriz de matrizes de tipos.An array of arrays of types. Cada matriz de tipos representa os modificadores personalizados opcionais para o parâmetro correspondente, por exemplo IsConst.Each array of types represents the optional custom modifiers for the corresponding parameter, such as IsConst. Se um determinado parâmetro tiver não modificadores personalizados opcionais, especifique null em vez de uma matriz de tipos.If a particular parameter has no optional custom modifiers, specify null instead of an array of types. Se nenhum dos parâmetros tiver modificadores personalizados opcionais, especifique null em vez de uma matriz de matrizes.If none of the parameters have optional custom modifiers, specify null instead of an array of arrays.

Retornos

MethodBuilder

Um objeto MethodBuilder que representa o método recém-adicionado.A MethodBuilder object representing the newly added method.

Exceções

O comprimento de name é zero.The length of name is zero.

- ou --or- O tipo de pai desse método é uma interface e esse método não é virtual (Overridable no Visual Basic).The type of the parent of this method is an interface, and this method is not virtual (Overridable in Visual Basic).

- ou --or- O tamanho de parameterTypeRequiredCustomModifiers ou parameterTypeOptionalCustomModifiers não é igual ao tamanho de parameterTypes.The size of parameterTypeRequiredCustomModifiers or parameterTypeOptionalCustomModifiers does not equal the size of parameterTypes.

name é null.name is null.

O tipo foi criado anteriormente usando CreateType().The type was previously created using CreateType().

- ou --or- Para o tipo dinâmico atual, a propriedade IsGenericType é true, mas a propriedade IsGenericTypeDefinition é false.For the current dynamic type, the IsGenericType property is true, but the IsGenericTypeDefinition property is false.

Comentários

Use essa sobrecarga se você precisar especificar modificadores personalizados.Use this overload if you need to specify custom modifiers. Se você precisar especificar modificadores personalizados depois que o método tiver sido criado, como faria, por exemplo, com um método genérico cujos tipos de parâmetro são especificados por seus parâmetros de tipo genérico, você poderá usar DefineMethod(String, MethodAttributes) as DefineMethod(String, MethodAttributes, CallingConventions) sobrecargas de método ou para definir o método e, em seguida, usar o MethodBuilder.SetSignature método para definir o parâmetro e os tipos de retorno com modificadores personalizados.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.

Observação

Para obter mais informações sobre modificadores personalizados, consulte padrões ECMA C# e Common Language Infrastructure e a CLI (Standard ECMA-335-Common Language Infrastructure).For more information on custom modifiers, see ECMA C# and Common Language Infrastructure Standards and Standard ECMA-335 - Common Language Infrastructure (CLI).

Aplica-se a