MethodBuilder.DefineGenericParameters(String[]) 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 o número de parâmetros genéricos de tipo para o método atual, especifica os seus nomes e devolve um array de GenericTypeParameterBuilder objetos que podem ser usados para definir as suas restrições.
public:
cli::array <System::Reflection::Emit::GenericTypeParameterBuilder ^> ^ DefineGenericParameters(... cli::array <System::String ^> ^ names);
public System.Reflection.Emit.GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names);
member this.DefineGenericParameters : string[] -> System.Reflection.Emit.GenericTypeParameterBuilder[]
Public Function DefineGenericParameters (ParamArray names As String()) As GenericTypeParameterBuilder()
Parâmetros
- names
- String[]
Um array de cadeias que representam os nomes dos parâmetros genéricos do tipo.
Devoluções
Um array de GenericTypeParameterBuilder objetos que representa os parâmetros de tipo do método genérico.
Exceções
Parâmetros genéricos de tipo já foram definidos para este método.
-ou-
O método já foi concluído.
-ou-
O SetImplementationFlags(MethodImplAttributes) método foi chamado para o método atual.
names é um array vazio.
Exemplos
O seguinte exemplo de código cria um tipo dinâmico, DemoType, que contém o método DemoMethodgenérico dinâmico . Este método tem dois parâmetros genéricos de tipo, um dos quais é usado como parâmetro e o outro como tipo de retorno.
Quando o código é executado, o assembly dinâmico é salvo como DemoGenericMethod1.dlle pode ser examinado usando o Ildasm.exe (IL Disassembler).
Note
Este exemplo de código gera um corpo de método simples que apenas devolve uma referência nula. Para um exemplo de código com um corpo de método mais desenvolvido que cria e utiliza tipos genéricos, veja Como: Definir um Método Genérico com Emissão por Reflexão.
using System;
using System.Reflection;
using System.Reflection.Emit;
class DemoMethodBuilder
{
public static void Main()
{
// Creating a dynamic assembly requires an AssemblyName
// object, and the current application domain.
//
AssemblyName asmName =
new AssemblyName("DemoMethodBuilder1");
AppDomain domain = AppDomain.CurrentDomain;
AssemblyBuilder demoAssembly =
domain.DefineDynamicAssembly(
asmName,
AssemblyBuilderAccess.RunAndSave
);
// Define the module that contains the code. For an
// assembly with one module, the module name is the
// assembly name plus a file extension.
ModuleBuilder demoModule =
demoAssembly.DefineDynamicModule(
asmName.Name,
asmName.Name + ".dll"
);
TypeBuilder demoType = demoModule.DefineType(
"DemoType",
TypeAttributes.Public | TypeAttributes.Abstract
);
// 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
);
// 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);
// Use the IsGenericMethod property to find out if a
// dynamic method is generic, and IsGenericMethodDefinition
// to find out if it defines a generic method.
Console.WriteLine("Is DemoMethod generic? {0}",
demoMethod.IsGenericMethod);
Console.WriteLine("Is DemoMethod a generic method definition? {0}",
demoMethod.IsGenericMethodDefinition);
// 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]);
// Generate a code body for the method. The method doesn't
// do anything except return null.
//
ILGenerator ilgen = demoMethod.GetILGenerator();
ilgen.Emit(OpCodes.Ldnull);
ilgen.Emit(OpCodes.Ret);
// Complete the type.
Type dt = demoType.CreateType();
// To bind types to a dynamic generic method, you must
// first call the GetMethod method on the completed type.
// You can then define an array of types, and bind them
// to the method.
MethodInfo m = dt.GetMethod("DemoMethod");
Type[] typeArgs = {typeof(string), typeof(DemoMethodBuilder)};
MethodInfo bound = m.MakeGenericMethod(typeArgs);
// Display a string representing the bound method.
Console.WriteLine(bound);
// Save the assembly, so it can be examined with Ildasm.exe.
demoAssembly.Save(asmName.Name + ".dll");
}
}
/* This code example produces the following output:
Is DemoMethod generic? True
Is DemoMethod a generic method definition? True
DemoMethodBuilder DemoMethod[String,DemoMethodBuilder](System.String)
*/
Imports System.Reflection
Imports System.Reflection.Emit
Class DemoMethodBuilder
Public Shared Sub Main()
' Creating a dynamic assembly requires an AssemblyName
' object, and the current application domain.
'
Dim asmName As New AssemblyName("DemoMethodBuilder1")
Dim domain As AppDomain = AppDomain.CurrentDomain
Dim demoAssembly As AssemblyBuilder = _
domain.DefineDynamicAssembly(asmName, _
AssemblyBuilderAccess.RunAndSave)
' Define the module that contains the code. For an
' assembly with one module, the module name is the
' assembly name plus a file extension.
Dim demoModule As ModuleBuilder = _
demoAssembly.DefineDynamicModule( _
asmName.Name, _
asmName.Name & ".dll")
Dim demoType As TypeBuilder = demoModule.DefineType( _
"DemoType", _
TypeAttributes.Public Or TypeAttributes.Abstract)
' 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.
'
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)
' Use the IsGenericMethod property to find out if a
' dynamic method is generic, and IsGenericMethodDefinition
' to find out if it defines a generic method.
Console.WriteLine("Is DemoMethod generic? {0}", _
demoMethod.IsGenericMethod)
Console.WriteLine("Is DemoMethod a generic method definition? {0}", _
demoMethod.IsGenericMethodDefinition)
' 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))
' Generate a code body for the method. The method doesn't
' do anything except return Nothing.
'
Dim ilgen As ILGenerator = demoMethod.GetILGenerator()
ilgen.Emit(OpCodes.Ldnull)
ilgen.Emit(OpCodes.Ret)
' Complete the type.
Dim dt As Type = demoType.CreateType()
' To bind types to a dynamic generic method, you must
' first call the GetMethod method on the completed type.
' You can then define an array of types, and bind them
' to the method.
Dim m As MethodInfo = dt.GetMethod("DemoMethod")
Dim typeArgs() As Type = _
{GetType(String), GetType(DemoMethodBuilder)}
Dim bound As MethodInfo = m.MakeGenericMethod(typeArgs)
' Display a string representing the bound method.
Console.WriteLine(bound)
' Save the assembly, so it can be examined with Ildasm.exe.
demoAssembly.Save(asmName.Name & ".dll")
End Sub
End Class
' This code example produces the following output:
'Is DemoMethod generic? True
'Is DemoMethod a generic method definition? True
'DemoMethodBuilder DemoMethod[String,DemoMethodBuilder](System.String)
Observações
Chamar o DefineGenericParameters método torna o método atual genérico. Não há forma de reverter esta mudança. Chamar este método uma segunda vez causa um InvalidOperationException.
Os parâmetros de tipo do método genérico podem ser recuperados mais tarde usando o GetGenericArguments método.
Por convenção, o nome de um parâmetro de tipo é uma única letra maiúscula.
Para obter mais informações, consulte MethodBase.IsGenericMethod e MethodInfo.GetGenericMethodDefinition. Para informações sobre tipos genéricos, veja Type.IsGenericType.