MethodBuilder.SetSignature Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Define a assinatura do método, incluindo o tipo de retorno, os tipos de parâmetros e os modificadores personalizados obrigatórios e opcionais do tipo de retorno e dos tipos de parâmetro.
public:
void SetSignature(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 void SetSignature(Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers);
member this.SetSignature : Type * Type[] * Type[] * Type[] * Type[][] * Type[][] -> unit
Public Sub SetSignature (returnType As Type, returnTypeRequiredCustomModifiers As Type(), returnTypeOptionalCustomModifiers As Type(), parameterTypes As Type(), parameterTypeRequiredCustomModifiers As Type()(), parameterTypeOptionalCustomModifiers As Type()())
Parâmetros
- returnType
- Type
O tipo de retorno do método.
- returnTypeRequiredCustomModifiers
- Type[]
Um array de tipos que representam os modificadores personalizados necessários, como IsConst, para o tipo de retorno do método. Se o tipo de retorno não tiver modificadores personalizados obrigatórios, especifique null.
- returnTypeOptionalCustomModifiers
- Type[]
Um array de tipos que representam os modificadores personalizados opcionais, como IsConst, para o tipo de retorno do método. Se o tipo de retorno não tiver modificadores personalizados opcionais, especifique null.
- parameterTypes
- Type[]
Os tipos de parâmetros do método.
- parameterTypeRequiredCustomModifiers
- Type[][]
Uma variedade de arrays de tipos. Cada array de tipos representa os modificadores personalizados necessários para o parâmetro correspondente, como IsConst. Se um determinado parâmetro não tiver modificadores personalizados obrigatórios, especifique null em vez disso um array de tipos. Se nenhum dos parâmetros exigir modificadores personalizados, especifique null em vez de um array de arrays.
- parameterTypeOptionalCustomModifiers
- Type[][]
Uma variedade de arrays de tipos. Cada array de tipos representa os modificadores personalizados opcionais para o parâmetro correspondente, como IsConst. Se um determinado parâmetro não tiver modificadores personalizados opcionais, especifique null em vez disso um array de tipos. Se nenhum dos parâmetros tiver modificadores personalizados opcionais, especifique null em vez de um array de arrays.
Exceções
O método atual é genérico, mas não é uma definição genérica de método. Ou seja, a IsGenericMethod propriedade é true, mas a IsGenericMethodDefinition propriedade é false.
Exemplos
O seguinte exemplo de código contém código-fonte para uma classe genérica chamada Sample que tem um parâmetro Tde tipo . A classe tem um corpo chamado Field, de tipo T, e um método GM genérico com o seu próprio parâmetro de tipo, U. O método GM cria uma instância de Sample, substituindo o seu próprio parâmetro U de tipo pelo parâmetro de tipo de Sample, e armazena o seu parâmetro de entrada em Field. Este código-fonte é compilado mas não é utilizado; pode visualizá-lo com o Ildasm.exe (IL Disassembler) e compará-lo com o código emitido pela classe Example.
O código na aula Example demonstra a utilização do SetSignature método na emissão de código genérico. O Main método de classe Example cria um conjunto dinâmico contendo uma classe chamada Sample, e usa o TypeBuilder.DefineGenericParameters método para a tornar genérica adicionando um parâmetro de tipo chamado T. Um construtor sem parâmetros e um corpo nomeado Field, de tipo T, são adicionados à classe Sample. Um método GM é adicionado e transformado num método genérico usando o DefineGenericParameters método. O parâmetro tipo de GM é chamado U. Uma vez definido o parâmetro de tipo, a assinatura de GM é adicionada, usando o SetSignature método. Não existe um tipo de retorno, nem modificadores obrigatórios ou personalizados, pelo que todos os parâmetros deste método são null exceto parameterTypes, que define o tipo do único parâmetro do método; este é definido para o parâmetro de tipo do método, U. O corpo do método cria uma instância do tipo construído Sample<U> (Sample(Of U) em Visual Basic), atribui o parâmetro do método a Field e depois imprime o valor de Field. Um tipo fictício é definido, para conter o método Maindo ponto de entrada . No corpo de Main, o método estático GM é invocado no tipo genérico construído Sample<int> (Sample(Of Integer) em Visual Basic), substituindo o tipo StringU. O TypeBuilder.GetMethod método é usado para criar um MethodInfo para o método estático GM do tipo Sample<U>genérico construído , e o MethodInfo.MakeGenericMethod método é então usado para criar um MethodInfo que pode ser emitido numa chamada de método.
Quando o exemplo de código é executado, ele guarda o conjunto emitido como TypeBuilderGetFieldExample.exe. Podes correr TypeBuilderGetFieldExample.exe, e podes usar o Ildasm.exe (IL Disassembler) para comparar o código emitido com o código da Sample classe que é compilado no próprio exemplo de código.
using System;
using System.Reflection;
using System.Reflection.Emit;
// Compare the MSIL in this class to the MSIL
// generated by the Reflection.Emit code in class
// Example.
public class Sample<T>
{
public T Field;
public static void GM<U>(U val)
{
Sample<U> s = new Sample<U>();
s.Field = val;
Console.WriteLine(s.Field);
}
}
public class Example
{
public static void Main()
{
AppDomain myDomain = AppDomain.CurrentDomain;
AssemblyName myAsmName =
new AssemblyName("TypeBuilderGetFieldExample");
AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(
myAsmName, AssemblyBuilderAccess.Save);
ModuleBuilder myModule = myAssembly.DefineDynamicModule(
myAsmName.Name,
myAsmName.Name + ".exe");
// Define the sample type.
TypeBuilder myType = myModule.DefineType("Sample",
TypeAttributes.Class | TypeAttributes.Public);
// Add a type parameter, making the type generic.
string[] typeParamNames = {"T"};
GenericTypeParameterBuilder[] typeParams =
myType.DefineGenericParameters(typeParamNames);
// Define a default constructor. Normally it would
// not be necessary to define the default constructor,
// but in this case it is needed for the call to
// TypeBuilder.GetConstructor, which gets the default
// constructor for the generic type constructed from
// Sample<T>, in the generic method GM<U>.
ConstructorBuilder ctor = myType.DefineDefaultConstructor(
MethodAttributes.PrivateScope | MethodAttributes.Public |
MethodAttributes.HideBySig | MethodAttributes.SpecialName |
MethodAttributes.RTSpecialName);
// Add a field of type T, with the name Field.
FieldBuilder myField = myType.DefineField("Field",
typeParams[0],
FieldAttributes.Public);
// Add a method and make it generic, with a type
// parameter named U. Note how similar this is to
// the way Sample is turned into a generic type. The
// method has no signature, because the type of its
// only parameter is U, which is not yet defined.
MethodBuilder genMethod = myType.DefineMethod("GM",
MethodAttributes.Public | MethodAttributes.Static);
string[] methodParamNames = {"U"};
GenericTypeParameterBuilder[] methodParams =
genMethod.DefineGenericParameters(methodParamNames);
// Now add a signature for genMethod, specifying U
// as the type of the parameter. There is no return value
// and no custom modifiers.
genMethod.SetSignature(null, null, null,
new Type[] { methodParams[0] }, null, null);
// Emit a method body for the generic method.
ILGenerator ilg = genMethod.GetILGenerator();
// Construct the type Sample<U> using MakeGenericType.
Type SampleOfU = myType.MakeGenericType( methodParams[0] );
// Create a local variable to store the instance of
// Sample<U>.
ilg.DeclareLocal(SampleOfU);
// Call the default constructor. Note that it is
// necessary to have the default constructor for the
// constructed generic type Sample<U>; use the
// TypeBuilder.GetConstructor method to obtain this
// constructor.
ConstructorInfo ctorOfU = TypeBuilder.GetConstructor(
SampleOfU, ctor);
ilg.Emit(OpCodes.Newobj, ctorOfU);
// Store the instance in the local variable; load it
// again, and load the parameter of genMethod.
ilg.Emit(OpCodes.Stloc_0);
ilg.Emit(OpCodes.Ldloc_0);
ilg.Emit(OpCodes.Ldarg_0);
// In order to store the value in the field of the
// instance of Sample<U>, it is necessary to have
// a FieldInfo representing the field of the
// constructed type. Use TypeBuilder.GetField to
// obtain this FieldInfo.
FieldInfo FieldOfU = TypeBuilder.GetField(
SampleOfU, myField);
// Store the value in the field.
ilg.Emit(OpCodes.Stfld, FieldOfU);
// Load the instance, load the field value, box it
// (specifying the type of the type parameter, U), and
// print it.
ilg.Emit(OpCodes.Ldloc_0);
ilg.Emit(OpCodes.Ldfld, FieldOfU);
ilg.Emit(OpCodes.Box, methodParams[0]);
MethodInfo writeLineObj =
typeof(Console).GetMethod("WriteLine",
new Type[] { typeof(object) });
ilg.EmitCall(OpCodes.Call, writeLineObj, null);
ilg.Emit(OpCodes.Ret);
// Emit an entry point method; this must be in a
// non-generic type.
TypeBuilder dummy = myModule.DefineType("Dummy",
TypeAttributes.Class | TypeAttributes.NotPublic);
MethodBuilder entryPoint = dummy.DefineMethod("Main",
MethodAttributes.Public | MethodAttributes.Static,
null, null);
ilg = entryPoint.GetILGenerator();
// In order to call the static generic method GM, it is
// necessary to create a constructed type from the
// generic type definition for Sample. This can be any
// constructed type; in this case Sample<int> is used.
Type SampleOfInt =
myType.MakeGenericType( typeof(int) );
// Next get a MethodInfo representing the static generic
// method GM on type Sample<int>.
MethodInfo SampleOfIntGM = TypeBuilder.GetMethod(SampleOfInt,
genMethod);
// Next get a MethodInfo for GM<string>, which is the
// instantiation of GM that Main calls.
MethodInfo GMOfString =
SampleOfIntGM.MakeGenericMethod( typeof(string) );
// Finally, emit the call. Push a string onto
// the stack, as the argument for the generic method.
ilg.Emit(OpCodes.Ldstr, "Hello, world!");
ilg.EmitCall(OpCodes.Call, GMOfString, null);
ilg.Emit(OpCodes.Ret);
myType.CreateType();
dummy.CreateType();
myAssembly.SetEntryPoint(entryPoint);
myAssembly.Save(myAsmName.Name + ".exe");
Console.WriteLine(myAsmName.Name + ".exe has been saved.");
}
}
Imports System.Reflection
Imports System.Reflection.Emit
' Compare the MSIL in this class to the MSIL
' generated by the Reflection.Emit code in class
' Example.
Public Class Sample(Of T)
Public Field As T
Public Shared Sub GM(Of U)(ByVal val As U)
Dim s As New Sample(Of U)
s.Field = val
Console.WriteLine(s.Field)
End Sub
End Class
Public Class Example
Public Shared Sub Main()
Dim myDomain As AppDomain = AppDomain.CurrentDomain
Dim myAsmName As New AssemblyName("TypeBuilderGetFieldExample")
Dim myAssembly As AssemblyBuilder = _
myDomain.DefineDynamicAssembly(myAsmName, _
AssemblyBuilderAccess.Save)
Dim myModule As ModuleBuilder = _
myAssembly.DefineDynamicModule(myAsmName.Name, _
myAsmName.Name & ".exe")
' Define the sample type.
Dim myType As TypeBuilder = myModule.DefineType( _
"Sample", _
TypeAttributes.Class Or TypeAttributes.Public)
' Add a type parameter, making the type generic.
Dim typeParamNames() As String = { "T" }
Dim typeParams As GenericTypeParameterBuilder() = _
myType.DefineGenericParameters(typeParamNames)
' Define a default constructor. Normally it would
' not be necessary to define the default constructor,
' but in this case it is needed for the call to
' TypeBuilder.GetConstructor, which gets the default
' constructor for the generic type constructed from
' Sample(Of T), in the generic method GM(Of U).
Dim ctor As ConstructorBuilder = _
myType.DefineDefaultConstructor( _
MethodAttributes.PrivateScope Or MethodAttributes.Public _
Or MethodAttributes.HideBySig Or MethodAttributes.SpecialName _
Or MethodAttributes.RTSpecialName)
' Add a field of type T, with the name Field.
Dim myField As FieldBuilder = myType.DefineField( _
"Field", typeParams(0), FieldAttributes.Public)
' Add a method and make it generic, with a type
' parameter named U. Note how similar this is to
' the way Sample is turned into a generic type. The
' method has no signature, because the type of its
' only parameter is U, which is not yet defined.
Dim genMethod As MethodBuilder = _
myType.DefineMethod("GM", _
MethodAttributes.Public Or MethodAttributes.Static)
Dim methodParamNames() As String = { "U" }
Dim methodParams As GenericTypeParameterBuilder() = _
genMethod.DefineGenericParameters(methodParamNames)
' Now add a signature for genMethod, specifying U
' as the type of the parameter. There is no return value
' and no custom modifiers.
genMethod.SetSignature(Nothing, Nothing, Nothing, _
New Type() { methodParams(0) }, Nothing, Nothing)
' Emit a method body for the generic method.
Dim ilg As ILGenerator = genMethod.GetILGenerator()
' Construct the type Sample(Of U) using MakeGenericType.
Dim SampleOfU As Type = _
myType.MakeGenericType(methodParams(0))
' Create a local variable to store the instance of
' Sample(Of U).
ilg.DeclareLocal(SampleOfU)
' Call the default constructor. Note that it is
' necessary to have the default constructor for the
' constructed generic type Sample(Of U); use the
' TypeBuilder.GetConstructor method to obtain this
' constructor.
Dim ctorOfU As ConstructorInfo = _
TypeBuilder.GetConstructor(SampleOfU, ctor)
ilg.Emit(OpCodes.Newobj, ctorOfU)
' Store the instance in the local variable; load it
' again, and load the parameter of genMethod.
ilg.Emit(OpCodes.Stloc_0)
ilg.Emit(OpCodes.Ldloc_0)
ilg.Emit(OpCodes.Ldarg_0)
' In order to store the value in the field of the
' instance of Sample(Of U), it is necessary to have
' a FieldInfo representing the field of the
' constructed type. Use TypeBuilder.GetField to
' obtain this FieldInfo.
Dim FieldOfU As FieldInfo = _
TypeBuilder.GetField(SampleOfU, myField)
' Store the value in the field.
ilg.Emit(OpCodes.Stfld, FieldOfU)
' Load the instance, load the field value, box it
' (specifying the type of the type parameter, U),
' and print it.
ilg.Emit(OpCodes.Ldloc_0)
ilg.Emit(OpCodes.Ldfld, FieldOfU)
ilg.Emit(OpCodes.Box, methodParams(0))
Dim writeLineObj As MethodInfo = _
GetType(Console).GetMethod("WriteLine", _
New Type() {GetType(Object)})
ilg.EmitCall(OpCodes.Call, writeLineObj, Nothing)
ilg.Emit(OpCodes.Ret)
' Emit an entry point method; this must be in a
' non-generic type.
Dim dummy As TypeBuilder = _
myModule.DefineType("Dummy", _
TypeAttributes.Class Or TypeAttributes.NotPublic)
Dim entryPoint As MethodBuilder = _
dummy.DefineMethod("Main", _
MethodAttributes.Public Or MethodAttributes.Static, _
Nothing, Nothing)
ilg = entryPoint.GetILGenerator()
' In order to call the static generic method GM, it is
' necessary to create a constructed type from the
' generic type definition for Sample. This can be ANY
' constructed type; in this case Sample(Of Integer)
' is used.
Dim SampleOfInt As Type = _
myType.MakeGenericType(GetType(Integer))
' Next get a MethodInfo representing the static generic
' method GM on type Sample(Of Integer).
Dim SampleOfIntGM As MethodInfo = _
TypeBuilder.GetMethod(SampleOfInt, genMethod)
' Next get a MethodInfo for GM(Of String), which is the
' instantiation of generic method GM that is called
' by Sub Main.
Dim GMOfString As MethodInfo = _
SampleOfIntGM.MakeGenericMethod(GetType(String))
' Finally, emit the call. Push a string onto
' the stack, as the argument for the generic method.
ilg.Emit(OpCodes.Ldstr, "Hello, world!")
ilg.EmitCall(OpCodes.Call, GMOfString, Nothing)
ilg.Emit(OpCodes.Ret)
myType.CreateType()
dummy.CreateType()
myAssembly.SetEntryPoint(entryPoint)
myAssembly.Save(myAsmName.Name & ".exe")
Console.WriteLine(myAsmName.Name & ".exe has been saved.")
End Sub
End Class
Observações
Se o tipo de retorno e o número e tipos dos parâmetros forem conhecidos quando o método for definido, podem ser estabelecidos usando qualquer sobrecarga do TypeBuilder.DefineMethod método que aceite um array de tipos de parâmetros. No entanto, um método genérico pode ter parâmetros cujos tipos são especificados por um ou mais dos seus próprios parâmetros genéricos, que não podem ser definidos até depois de o método ter sido definido. Use este método para definir os tipos de parâmetros nesse caso.
Se nem o tipo return nem os tipos de parâmetros tiverem modificadores personalizados opcionais ou obrigatórios, como IsConstModifier, pode usar os SetReturnType métodos e.SetParameters
Chamar este método substitui os parâmetros e o tipo de retorno estabelecidos pelo TypeBuilder.DefineMethod método.