TypeBuilder.DefineMethod Methode

Definition

Fügt dem Typ eine Methode hinzu.

Überlädt

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

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen, der Aufrufkonvention, der Methodensignatur und den benutzerdefinierten Modifizierern hinzu.

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

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen, der Aufrufkonvention und der Methodensignatur hinzu.

DefineMethod(String, MethodAttributes, CallingConventions)

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen und der Aufrufkonvention hinzu.

DefineMethod(String, MethodAttributes)

Fügt eine neue Methode zum Typ mit dem angegebenen Namen und den Methodenattributen hinzu.

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

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen und der Methodensignatur hinzu.

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

Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen, der Aufrufkonvention, der Methodensignatur und den benutzerdefinierten Modifizierern hinzu.

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

Parameter

name
String

Der Name der Methode. name darf keine eingebetteten NULL-Werte enthalten.

attributes
MethodAttributes

Die Attribute der Methode.

callingConvention
CallingConventions

Die Aufrufkonvention der Methode.

returnType
Type

Der Rückgabetyp der Methode.

returnTypeRequiredCustomModifiers
Type[]

Ein Array von Typen, die die erforderlichen benutzerdefinierten Modifizierer, etwa IsConst, für den Rückgabetyp der Methode darstellen. Wenn der Rückgabetyp keine erforderlichen benutzerdefinierten Modifizierer hat, geben Sie nullan.

returnTypeOptionalCustomModifiers
Type[]

Ein Array von Typen, die die optionalen benutzerdefinierten Modifizierer, etwa IsConst, für den Rückgabetyp der Methode darstellen. Wenn der Rückgabetyp keine optionalen benutzerdefinierten Modifizierer hat, geben Sie null an.

parameterTypes
Type[]

Die Typen der Parameter der Methode.

parameterTypeRequiredCustomModifiers
Type[][]

Ein Array mit Arrays von Typen. Jedes Array von Typen stellt die erforderlichen benutzerdefinierten Modifizierer für den entsprechenden Parameter dar, z. B. IsConst. Wenn ein bestimmter Parameter keine erforderlichen benutzerdefinierten Modifizierer hat, geben Sie null anstelle eines Arrays von Typen an. Wenn keiner der Parameter erforderliche benutzerdefinierte Modifizierer hat, geben Sie null anstelle eines Arrays mit Arrays an.

parameterTypeOptionalCustomModifiers
Type[][]

Ein Array mit Arrays von Typen. Jedes Array von Typen stellt die optionalen benutzerdefinierten Modifizierer für den entsprechenden Parameter dar, z. B. IsConst. Wenn ein bestimmter Parameter keine optionalen benutzerdefinierten Modifizierer hat, geben Sie null anstelle eines Arrays von Typen an. Wenn keiner der Parameter optionale benutzerdefinierte Modifizierer hat, geben Sie null anstelle eines Arrays mit Arrays an.

Gibt zurück

Ein MethodBuilder-Objekt, das die neu hinzugefügte Methode darstellt.

Ausnahmen

Die Länge von name ist 0 (null).

- oder -

Der Typ des übergeordneten Elements dieser Methode ist eine Schnittstelle, und diese Methode ist nicht virtuell (Overridable in Visual Basic).

- oder -

Die Größe von parameterTypeRequiredCustomModifiers oder parameterTypeOptionalCustomModifiers entspricht nicht die Größe von parameterTypes.

name ist null.

Der Typ wurde zuvor mit CreateType()erstellt.

- oder -

Für den aktuellen dynamischen Typ ist die IsGenericType-Eigenschaft true, aber die IsGenericTypeDefinition-Eigenschaft ist false.

Hinweise

Verwenden Sie diese Überladung, wenn Sie benutzerdefinierte Modifizierer angeben müssen. Wenn Sie benutzerdefinierte Modifizierer angeben müssen, nachdem die Methode erstellt wurde, wie z. B. bei einer generischen Methode, deren Parametertypen durch ihre generischen Typparameter angegeben werden, können Sie die DefineMethod(String, MethodAttributes) - oder DefineMethod(String, MethodAttributes, CallingConventions) -Methodenüberladungen verwenden, um die -Methode zu definieren und dann mit der MethodBuilder.SetSignature -Methode den Parameter zu definieren und Typen mit benutzerdefinierten Modifizierern zurückzugeben.

Hinweis

Weitere Informationen zu benutzerdefinierten Modifizierern finden Sie unter ECMA C# und Common Language Infrastructure Standards und Standard ECMA-335 – Common Language Infrastructure (CLI).

Gilt für:

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

Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen, der Aufrufkonvention und der Methodensignatur hinzu.

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

Parameter

name
String

Der Name der Methode. name darf keine eingebetteten NULL-Werte enthalten.

attributes
MethodAttributes

Die Attribute der Methode.

callingConvention
CallingConventions

Die Aufrufkonvention der Methode.

returnType
Type

Der Rückgabetyp der Methode.

parameterTypes
Type[]

Die Typen der Parameter der Methode.

Gibt zurück

Ein MethodBuilder, der die neu definierte Methode darstellt.

Ausnahmen

Die Länge von name ist 0 (null).

- oder -

Der Typ des übergeordneten Elements dieser Methode ist eine Schnittstelle, und diese Methode ist nicht virtuell (Overridable in Visual Basic).

name ist null.

Der Typ wurde zuvor mit CreateType()erstellt.

- oder -

Für den aktuellen dynamischen Typ ist die IsGenericType-Eigenschaft true, aber die IsGenericTypeDefinition-Eigenschaft ist false.

Beispiele

Im folgenden Codebeispiel wird die Verwendung von DefineMethod veranschaulicht, um die bestimmte Signatur und Attribute eines Konstruktors für einen dynamischen Typ festzulegen und eine entsprechende MethodBuilder MSIL-Population zurückzugeben.

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
{
   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

Gilt für:

DefineMethod(String, MethodAttributes, CallingConventions)

Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen und der Aufrufkonvention hinzu.

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

Parameter

name
String

Der Name der Methode. name darf keine eingebetteten NULL-Werte enthalten.

attributes
MethodAttributes

Die Attribute der Methode.

callingConvention
CallingConventions

Die Aufrufkonvention der Methode.

Gibt zurück

Ein MethodBuilder, der die neu definierte Methode darstellt.

Ausnahmen

Die Länge von name ist 0 (null).

- oder -

Der Typ des übergeordneten Elements dieser Methode ist eine Schnittstelle, und diese Methode ist nicht virtuell (Overridable in Visual Basic).

name ist null.

Der Typ wurde zuvor mit CreateType()erstellt.

- oder -

Für den aktuellen dynamischen Typ ist die IsGenericType-Eigenschaft true, aber die IsGenericTypeDefinition-Eigenschaft ist false.

Hinweise

Verwenden Sie diese Methodenüberladung, wenn Sie die Methodensignatur zum Zeitpunkt der Definition der Methode nicht kennen. Beispielsweise können die Parametertypen und der Rückgabetyp einer generischen Methode durch die generischen Typparameter der Methode angegeben werden, die definiert werden müssen, nachdem die Methode dem Typ hinzugefügt wurde. Die Parameter und der Rückgabetyp der Methode können später mithilfe der MethodBuilder.SetSignature -Methode festgelegt werden.

Weitere Informationen

Gilt für:

DefineMethod(String, MethodAttributes)

Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs

Fügt eine neue Methode zum Typ mit dem angegebenen Namen und den Methodenattributen hinzu.

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

Parameter

name
String

Der Name der Methode. name darf keine eingebetteten NULL-Werte enthalten.

attributes
MethodAttributes

Die Attribute der Methode.

Gibt zurück

Ein MethodBuilder, der die neu definierte Methode darstellt.

Ausnahmen

Die Länge von name ist 0 (null).

- oder -

Der Typ des übergeordneten Elements dieser Methode ist eine Schnittstelle, und diese Methode ist nicht virtuell (Overridable in Visual Basic).

name ist null.

Der Typ wurde zuvor mit CreateType()erstellt.

- oder -

Für den aktuellen dynamischen Typ ist die IsGenericType-Eigenschaft true, aber die IsGenericTypeDefinition-Eigenschaft ist false.

Beispiele

Im folgenden Codebeispiel wird eine generische Methode mit dem Namen DemoMethod definiert, deren Parametertyp und Rückgabetyp durch ihre generischen Typparameter angegeben werden. Die Methode wird ohne Signatur mithilfe der Standardaufrufkonvention definiert. Die MethodBuilder.DefineGenericParameters -Methode wird verwendet, um eine generische Methode zu erstellen DemoMethod , und die neu definierten Typparameter werden dann für die Signatur und den Rückgabetyp verwendet.

Dieses Codebeispiel ist Teil eines größeren Beispiels für die DefineGenericParameters -Methode.

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

Hinweise

Verwenden Sie diese Methodenüberladung, wenn Sie die Methodensignatur zum Zeitpunkt der Definition der Methode nicht kennen. Beispielsweise können die Parametertypen und der Rückgabetyp einer generischen Methode durch die generischen Typparameter der Methode angegeben werden, die definiert werden müssen, nachdem die Methode dem Typ hinzugefügt wurde. Die Parameter und der Rückgabetyp der Methode können später mithilfe der MethodBuilder.SetSignature -Methode festgelegt werden.

Diese Methodenüberladung definiert eine Methode mit CallingConventions.Standard. Wenn Sie eine Methode ohne Signatur mit einer anderen Aufrufkonvention definieren müssen, verwenden Sie die DefineMethod(String, MethodAttributes, CallingConventions) Methodenüberladung.

Weitere Informationen

Gilt für:

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

Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs
Quelle:
TypeBuilder.cs

Fügt eine neue Methode zum Typ mit dem angegebenen Namen, den Methodenattributen und der Methodensignatur hinzu.

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

Parameter

name
String

Der Name der Methode. name darf keine eingebetteten NULL-Werte enthalten.

attributes
MethodAttributes

Die Attribute der Methode.

returnType
Type

Der Rückgabetyp der Methode.

parameterTypes
Type[]

Die Typen der Parameter der Methode.

Gibt zurück

Die definierte Methode.

Ausnahmen

Die Länge von name ist 0 (null).

- oder -

Der Typ des übergeordneten Elements dieser Methode ist eine Schnittstelle, und diese Methode ist nicht virtuell (Overridable in Visual Basic).

name ist null.

Der Typ wurde zuvor mit CreateType()erstellt.

- oder -

Für den aktuellen dynamischen Typ ist die IsGenericType-Eigenschaft true, aber die IsGenericTypeDefinition-Eigenschaft ist false.

Beispiele

Im folgenden Codebeispiel wird die Verwendung von DefineMethod veranschaulicht, um die bestimmte Signatur und Attribute eines Konstruktors für einen dynamischen Typ festzulegen und eine entsprechende MethodBuilder MSIL-Population zurückzugeben.

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
{
   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

Gilt für: