GenericTypeParameterBuilder 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。
public ref class GenericTypeParameterBuilder sealed : Type
public ref class GenericTypeParameterBuilder sealed : System::Reflection::TypeInfo
public ref class GenericTypeParameterBuilder abstract : System::Reflection::TypeInfo
public sealed class GenericTypeParameterBuilder : Type
public sealed class GenericTypeParameterBuilder : System.Reflection.TypeInfo
public abstract class GenericTypeParameterBuilder : System.Reflection.TypeInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder : Type
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder : System.Reflection.TypeInfo
type GenericTypeParameterBuilder = class
inherit Type
type GenericTypeParameterBuilder = class
inherit TypeInfo
[<System.Runtime.InteropServices.ComVisible(true)>]
type GenericTypeParameterBuilder = class
inherit Type
[<System.Runtime.InteropServices.ComVisible(true)>]
type GenericTypeParameterBuilder = class
inherit TypeInfo
Public NotInheritable Class GenericTypeParameterBuilder
Inherits Type
Public NotInheritable Class GenericTypeParameterBuilder
Inherits TypeInfo
Public MustInherit Class GenericTypeParameterBuilder
Inherits TypeInfo
- 继承
- 继承
- 继承
- 属性
示例
下面的代码示例创建一个具有两个类型参数的泛型类型,并将其保存在程序集 GenericEmitExample1.dll 中。 可以使用 Ildasm.exe (IL 反汇编程序) 查看生成的类型。 有关定义动态泛型类型所涉及的步骤的更详细说明,请参阅 如何:使用反射发出定义泛型类型。
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
using namespace System::Collections::Generic;
// Dummy class to satisfy TFirst constraints.
//
public ref class Example {};
// Define a trivial base class and two trivial interfaces
// to use when demonstrating constraints.
//
public ref class ExampleBase {};
public interface class IExampleA {};
public interface class IExampleB {};
// Define a trivial type that can substitute for type parameter
// TSecond.
//
public ref class ExampleDerived : ExampleBase, IExampleA, IExampleB {};
// List the constraint flags. The GenericParameterAttributes
// enumeration contains two sets of attributes, variance and
// constraints. For this example, only constraints are used.
//
static void ListConstraintAttributes( Type^ t )
{
// Mask off the constraint flags.
GenericParameterAttributes constraints =
t->GenericParameterAttributes &
GenericParameterAttributes::SpecialConstraintMask;
if ((constraints & GenericParameterAttributes::ReferenceTypeConstraint)
!= GenericParameterAttributes::None)
Console::WriteLine( L" ReferenceTypeConstraint");
if ((constraints & GenericParameterAttributes::NotNullableValueTypeConstraint)
!= GenericParameterAttributes::None)
Console::WriteLine( L" NotNullableValueTypeConstraint");
if ((constraints & GenericParameterAttributes::DefaultConstructorConstraint)
!= GenericParameterAttributes::None)
Console::WriteLine( L" DefaultConstructorConstraint");
}
static void DisplayGenericParameters( Type^ t )
{
if (!t->IsGenericType)
{
Console::WriteLine( L"Type '{0}' is not generic." );
return;
}
if (!t->IsGenericTypeDefinition)
t = t->GetGenericTypeDefinition();
array<Type^>^ typeParameters = t->GetGenericArguments();
Console::WriteLine( L"\r\nListing {0} type parameters for type '{1}'.",
typeParameters->Length, t );
for each ( Type^ tParam in typeParameters )
{
Console::WriteLine( L"\r\nType parameter {0}:",
tParam->ToString() );
for each (Type^ c in tParam->GetGenericParameterConstraints())
{
if (c->IsInterface)
Console::WriteLine( L" Interface constraint: {0}", c);
else
Console::WriteLine( L" Base type constraint: {0}", c);
}
ListConstraintAttributes(tParam);
}
}
void main()
{
// Define a dynamic assembly to contain the sample type. The
// assembly will be run and also saved to disk, so
// AssemblyBuilderAccess.RunAndSave is specified.
//
AppDomain^ myDomain = AppDomain::CurrentDomain;
AssemblyName^ myAsmName = gcnew AssemblyName( L"GenericEmitExample1" );
AssemblyBuilder^ myAssembly = myDomain->DefineDynamicAssembly(
myAsmName, AssemblyBuilderAccess::RunAndSave );
// An assembly is made up of executable modules. For a single-
// module assembly, the module name and file name are the same
// as the assembly name.
//
ModuleBuilder^ myModule = myAssembly->DefineDynamicModule(
myAsmName->Name, String::Concat( myAsmName->Name, L".dll" ) );
// Get type objects for the base class trivial interfaces to
// be used as constraints.
//
Type^ baseType = ExampleBase::typeid;
Type^ interfaceA = IExampleA::typeid;
Type^ interfaceB = IExampleB::typeid;
// Define the sample type.
//
TypeBuilder^ myType = myModule->DefineType( L"Sample",
TypeAttributes::Public );
Console::WriteLine( L"Type 'Sample' is generic: {0}",
myType->IsGenericType );
// Define type parameters for the type. Until you do this,
// the type is not generic, as the preceding and following
// WriteLine statements show. The type parameter names are
// specified as an array of strings. To make the code
// easier to read, each GenericTypeParameterBuilder is placed
// in a variable with the same name as the type parameter.
//
array<String^>^typeParamNames = {L"TFirst",L"TSecond"};
array<GenericTypeParameterBuilder^>^typeParams =
myType->DefineGenericParameters( typeParamNames );
GenericTypeParameterBuilder^ TFirst = typeParams[0];
GenericTypeParameterBuilder^ TSecond = typeParams[1];
Console::WriteLine( L"Type 'Sample' is generic: {0}",
myType->IsGenericType );
// Apply constraints to the type parameters.
//
// A type that is substituted for the first parameter, TFirst,
// must be a reference type and must have a parameterless
// constructor.
TFirst->SetGenericParameterAttributes(
GenericParameterAttributes::DefaultConstructorConstraint |
GenericParameterAttributes::ReferenceTypeConstraint
);
// A type that is substituted for the second type
// parameter must implement IExampleA and IExampleB, and
// inherit from the trivial test class ExampleBase. The
// interface constraints are specified as an array
// containing the interface types.
array<Type^>^interfaceTypes = { interfaceA, interfaceB };
TSecond->SetInterfaceConstraints( interfaceTypes );
TSecond->SetBaseTypeConstraint( baseType );
// The following code adds a private field named ExampleField,
// of type TFirst.
FieldBuilder^ exField =
myType->DefineField("ExampleField", TFirst,
FieldAttributes::Private);
// Define a static method that takes an array of TFirst and
// returns a List<TFirst> containing all the elements of
// the array. To define this method it is necessary to create
// the type List<TFirst> by calling MakeGenericType on the
// generic type definition, generic<T> List.
// The parameter type is created by using the
// MakeArrayType method.
//
Type^ listOf = List::typeid;
Type^ listOfTFirst = listOf->MakeGenericType(TFirst);
array<Type^>^ mParamTypes = { TFirst->MakeArrayType() };
MethodBuilder^ exMethod =
myType->DefineMethod("ExampleMethod",
MethodAttributes::Public | MethodAttributes::Static,
listOfTFirst,
mParamTypes);
// Emit the method body.
// The method body consists of just three opcodes, to load
// the input array onto the execution stack, to call the
// List<TFirst> constructor that takes IEnumerable<TFirst>,
// which does all the work of putting the input elements into
// the list, and to return, leaving the list on the stack. The
// hard work is getting the constructor.
//
// The GetConstructor method is not supported on a
// GenericTypeParameterBuilder, so it is not possible to get
// the constructor of List<TFirst> directly. There are two
// steps, first getting the constructor of generic<T> List and then
// calling a method that converts it to the corresponding
// constructor of List<TFirst>.
//
// The constructor needed here is the one that takes an
// IEnumerable<T>. Note, however, that this is not the
// generic type definition of generic<T> IEnumerable; instead, the
// T from generic<T> List must be substituted for the T of
// generic<T> IEnumerable. (This seems confusing only because both
// types have type parameters named T. That is why this example
// uses the somewhat silly names TFirst and TSecond.) To get
// the type of the constructor argument, take the generic
// type definition generic<T> IEnumerable and
// call MakeGenericType with the first generic type parameter
// of generic<T> List. The constructor argument list must be passed
// as an array, with just one argument in this case.
//
// Now it is possible to get the constructor of generic<T> List,
// using GetConstructor on the generic type definition. To get
// the constructor of List<TFirst>, pass List<TFirst> and
// the constructor from generic<T> List to the static
// TypeBuilder.GetConstructor method.
//
ILGenerator^ ilgen = exMethod->GetILGenerator();
Type^ ienumOf = IEnumerable::typeid;
Type^ TfromListOf = listOf->GetGenericArguments()[0];
Type^ ienumOfT = ienumOf->MakeGenericType(TfromListOf);
array<Type^>^ ctorArgs = {ienumOfT};
ConstructorInfo^ ctorPrep = listOf->GetConstructor(ctorArgs);
ConstructorInfo^ ctor =
TypeBuilder::GetConstructor(listOfTFirst, ctorPrep);
ilgen->Emit(OpCodes::Ldarg_0);
ilgen->Emit(OpCodes::Newobj, ctor);
ilgen->Emit(OpCodes::Ret);
// Create the type and save the assembly.
Type^ finished = myType->CreateType();
myAssembly->Save( String::Concat( myAsmName->Name, L".dll" ) );
// Invoke the method.
// ExampleMethod is not generic, but the type it belongs to is
// generic, so in order to get a MethodInfo that can be invoked
// it is necessary to create a constructed type. The Example
// class satisfies the constraints on TFirst, because it is a
// reference type and has a default constructor. In order to
// have a class that satisfies the constraints on TSecond,
// this code example defines the ExampleDerived type. These
// two types are passed to MakeGenericMethod to create the
// constructed type.
//
array<Type^>^ typeArgs =
{ Example::typeid, ExampleDerived::typeid };
Type^ constructed = finished->MakeGenericType(typeArgs);
MethodInfo^ mi = constructed->GetMethod("ExampleMethod");
// Create an array of Example objects, as input to the generic
// method. This array must be passed as the only element of an
// array of arguments. The first argument of Invoke is
// null, because ExampleMethod is static. Display the count
// on the resulting List<Example>.
//
array<Example^>^ input = { gcnew Example(), gcnew Example() };
array<Object^>^ arguments = { input };
List<Example^>^ listX =
(List<Example^>^) mi->Invoke(nullptr, arguments);
Console::WriteLine(
"\nThere are {0} elements in the List<Example>.",
listX->Count);
DisplayGenericParameters(finished);
}
/* This code example produces the following output:
Type 'Sample' is generic: False
Type 'Sample' is generic: True
There are 2 elements in the List<Example>.
Listing 2 type parameters for type 'Sample[TFirst,TSecond]'.
Type parameter TFirst:
ReferenceTypeConstraint
DefaultConstructorConstraint
Type parameter TSecond:
Interface constraint: IExampleA
Interface constraint: IExampleB
Base type constraint: ExampleBase
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
// Define a trivial base class and two trivial interfaces
// to use when demonstrating constraints.
//
public class ExampleBase {}
public interface IExampleA {}
public interface IExampleB {}
// Define a trivial type that can substitute for type parameter
// TSecond.
//
public class ExampleDerived : ExampleBase, IExampleA, IExampleB {}
public class Example
{
public static void Main()
{
// Define a dynamic assembly to contain the sample type. The
// assembly will not be run, but only saved to disk, so
// AssemblyBuilderAccess.Save is specified.
//
AppDomain myDomain = AppDomain.CurrentDomain;
AssemblyName myAsmName = new AssemblyName("GenericEmitExample1");
AssemblyBuilder myAssembly =
myDomain.DefineDynamicAssembly(myAsmName,
AssemblyBuilderAccess.RunAndSave);
// An assembly is made up of executable modules. For a single-
// module assembly, the module name and file name are the same
// as the assembly name.
//
ModuleBuilder myModule =
myAssembly.DefineDynamicModule(myAsmName.Name,
myAsmName.Name + ".dll");
// Get type objects for the base class trivial interfaces to
// be used as constraints.
//
Type baseType = typeof(ExampleBase);
Type interfaceA = typeof(IExampleA);
Type interfaceB = typeof(IExampleB);
// Define the sample type.
//
TypeBuilder myType =
myModule.DefineType("Sample", TypeAttributes.Public);
Console.WriteLine("Type 'Sample' is generic: {0}",
myType.IsGenericType);
// Define type parameters for the type. Until you do this,
// the type is not generic, as the preceding and following
// WriteLine statements show. The type parameter names are
// specified as an array of strings. To make the code
// easier to read, each GenericTypeParameterBuilder is placed
// in a variable with the same name as the type parameter.
//
string[] typeParamNames = {"TFirst", "TSecond"};
GenericTypeParameterBuilder[] typeParams =
myType.DefineGenericParameters(typeParamNames);
GenericTypeParameterBuilder TFirst = typeParams[0];
GenericTypeParameterBuilder TSecond = typeParams[1];
Console.WriteLine("Type 'Sample' is generic: {0}",
myType.IsGenericType);
// Apply constraints to the type parameters.
//
// A type that is substituted for the first parameter, TFirst,
// must be a reference type and must have a parameterless
// constructor.
TFirst.SetGenericParameterAttributes(
GenericParameterAttributes.DefaultConstructorConstraint |
GenericParameterAttributes.ReferenceTypeConstraint);
// A type that is substituted for the second type
// parameter must implement IExampleA and IExampleB, and
// inherit from the trivial test class ExampleBase. The
// interface constraints are specified as an array
// containing the interface types.
TSecond.SetBaseTypeConstraint(baseType);
Type[] interfaceTypes = {interfaceA, interfaceB};
TSecond.SetInterfaceConstraints(interfaceTypes);
// The following code adds a private field named ExampleField,
// of type TFirst.
FieldBuilder exField =
myType.DefineField("ExampleField", TFirst,
FieldAttributes.Private);
// Define a static method that takes an array of TFirst and
// returns a List<TFirst> containing all the elements of
// the array. To define this method it is necessary to create
// the type List<TFirst> by calling MakeGenericType on the
// generic type definition, List<T>. (The T is omitted with
// the typeof operator when you get the generic type
// definition.) The parameter type is created by using the
// MakeArrayType method.
//
Type listOf = typeof(List<>);
Type listOfTFirst = listOf.MakeGenericType(TFirst);
Type[] mParamTypes = {TFirst.MakeArrayType()};
MethodBuilder exMethod =
myType.DefineMethod("ExampleMethod",
MethodAttributes.Public | MethodAttributes.Static,
listOfTFirst,
mParamTypes);
// Emit the method body.
// The method body consists of just three opcodes, to load
// the input array onto the execution stack, to call the
// List<TFirst> constructor that takes IEnumerable<TFirst>,
// which does all the work of putting the input elements into
// the list, and to return, leaving the list on the stack. The
// hard work is getting the constructor.
//
// The GetConstructor method is not supported on a
// GenericTypeParameterBuilder, so it is not possible to get
// the constructor of List<TFirst> directly. There are two
// steps, first getting the constructor of List<T> and then
// calling a method that converts it to the corresponding
// constructor of List<TFirst>.
//
// The constructor needed here is the one that takes an
// IEnumerable<T>. Note, however, that this is not the
// generic type definition of IEnumerable<T>; instead, the
// T from List<T> must be substituted for the T of
// IEnumerable<T>. (This seems confusing only because both
// types have type parameters named T. That is why this example
// uses the somewhat silly names TFirst and TSecond.) To get
// the type of the constructor argument, take the generic
// type definition IEnumerable<T> (expressed as
// IEnumerable<> when you use the typeof operator) and
// call MakeGenericType with the first generic type parameter
// of List<T>. The constructor argument list must be passed
// as an array, with just one argument in this case.
//
// Now it is possible to get the constructor of List<T>,
// using GetConstructor on the generic type definition. To get
// the constructor of List<TFirst>, pass List<TFirst> and
// the constructor from List<T> to the static
// TypeBuilder.GetConstructor method.
//
ILGenerator ilgen = exMethod.GetILGenerator();
Type ienumOf = typeof(IEnumerable<>);
Type TfromListOf = listOf.GetGenericArguments()[0];
Type ienumOfT = ienumOf.MakeGenericType(TfromListOf);
Type[] ctorArgs = {ienumOfT};
ConstructorInfo ctorPrep = listOf.GetConstructor(ctorArgs);
ConstructorInfo ctor =
TypeBuilder.GetConstructor(listOfTFirst, ctorPrep);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Newobj, ctor);
ilgen.Emit(OpCodes.Ret);
// Create the type and save the assembly.
Type finished = myType.CreateType();
myAssembly.Save(myAsmName.Name+".dll");
// Invoke the method.
// ExampleMethod is not generic, but the type it belongs to is
// generic, so in order to get a MethodInfo that can be invoked
// it is necessary to create a constructed type. The Example
// class satisfies the constraints on TFirst, because it is a
// reference type and has a default constructor. In order to
// have a class that satisfies the constraints on TSecond,
// this code example defines the ExampleDerived type. These
// two types are passed to MakeGenericMethod to create the
// constructed type.
//
Type[] typeArgs = {typeof(Example), typeof(ExampleDerived)};
Type constructed = finished.MakeGenericType(typeArgs);
MethodInfo mi = constructed.GetMethod("ExampleMethod");
// Create an array of Example objects, as input to the generic
// method. This array must be passed as the only element of an
// array of arguments. The first argument of Invoke is
// null, because ExampleMethod is static. Display the count
// on the resulting List<Example>.
//
Example[] input = {new Example(), new Example()};
object[] arguments = {input};
List<Example> listX =
(List<Example>) mi.Invoke(null, arguments);
Console.WriteLine(
"\nThere are {0} elements in the List<Example>.",
listX.Count);
DisplayGenericParameters(finished);
}
private static void DisplayGenericParameters(Type t)
{
if (!t.IsGenericType)
{
Console.WriteLine("Type '{0}' is not generic.");
return;
}
if (!t.IsGenericTypeDefinition)
{
t = t.GetGenericTypeDefinition();
}
Type[] typeParameters = t.GetGenericArguments();
Console.WriteLine("\nListing {0} type parameters for type '{1}'.",
typeParameters.Length, t);
foreach( Type tParam in typeParameters )
{
Console.WriteLine("\r\nType parameter {0}:", tParam.ToString());
foreach( Type c in tParam.GetGenericParameterConstraints() )
{
if (c.IsInterface)
{
Console.WriteLine(" Interface constraint: {0}", c);
}
else
{
Console.WriteLine(" Base type constraint: {0}", c);
}
}
ListConstraintAttributes(tParam);
}
}
// List the constraint flags. The GenericParameterAttributes
// enumeration contains two sets of attributes, variance and
// constraints. For this example, only constraints are used.
//
private static void ListConstraintAttributes(Type t)
{
// Mask off the constraint flags.
GenericParameterAttributes constraints =
t.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
if ((constraints & GenericParameterAttributes.ReferenceTypeConstraint)
!= GenericParameterAttributes.None)
{
Console.WriteLine(" ReferenceTypeConstraint");
}
if ((constraints & GenericParameterAttributes.NotNullableValueTypeConstraint)
!= GenericParameterAttributes.None)
{
Console.WriteLine(" NotNullableValueTypeConstraint");
}
if ((constraints & GenericParameterAttributes.DefaultConstructorConstraint)
!=GenericParameterAttributes.None)
{
Console.WriteLine(" DefaultConstructorConstraint");
}
}
}
/* This code example produces the following output:
Type 'Sample' is generic: False
Type 'Sample' is generic: True
There are 2 elements in the List<Example>.
Listing 2 type parameters for type 'Sample[TFirst,TSecond]'.
Type parameter TFirst:
ReferenceTypeConstraint
DefaultConstructorConstraint
Type parameter TSecond:
Interface constraint: IExampleA
Interface constraint: IExampleB
Base type constraint: ExampleBase
*/
Imports System.Reflection
Imports System.Reflection.Emit
Imports System.Collections.Generic
' Define a trivial base class and two trivial interfaces
' to use when demonstrating constraints.
'
Public Class ExampleBase
End Class
Public Interface IExampleA
End Interface
Public Interface IExampleB
End Interface
' Define a trivial type that can substitute for type parameter
' TSecond.
'
Public Class ExampleDerived
Inherits ExampleBase
Implements IExampleA, IExampleB
End Class
Public Class Example
Public Shared Sub Main()
' Define a dynamic assembly to contain the sample type. The
' assembly will not be run, but only saved to disk, so
' AssemblyBuilderAccess.Save is specified.
'
Dim myDomain As AppDomain = AppDomain.CurrentDomain
Dim myAsmName As New AssemblyName("GenericEmitExample1")
Dim myAssembly As AssemblyBuilder = myDomain.DefineDynamicAssembly( _
myAsmName, _
AssemblyBuilderAccess.RunAndSave)
' An assembly is made up of executable modules. For a single-
' module assembly, the module name and file name are the same
' as the assembly name.
'
Dim myModule As ModuleBuilder = myAssembly.DefineDynamicModule( _
myAsmName.Name, _
myAsmName.Name & ".dll")
' Get type objects for the base class trivial interfaces to
' be used as constraints.
'
Dim baseType As Type = GetType(ExampleBase)
Dim interfaceA As Type = GetType(IExampleA)
Dim interfaceB As Type = GetType(IExampleB)
' Define the sample type.
'
Dim myType As TypeBuilder = myModule.DefineType( _
"Sample", _
TypeAttributes.Public)
Console.WriteLine("Type 'Sample' is generic: {0}", _
myType.IsGenericType)
' Define type parameters for the type. Until you do this,
' the type is not generic, as the preceding and following
' WriteLine statements show. The type parameter names are
' specified as an array of strings. To make the code
' easier to read, each GenericTypeParameterBuilder is placed
' in a variable with the same name as the type parameter.
'
Dim typeParamNames() As String = {"TFirst", "TSecond"}
Dim typeParams() As GenericTypeParameterBuilder = _
myType.DefineGenericParameters(typeParamNames)
Dim TFirst As GenericTypeParameterBuilder = typeParams(0)
Dim TSecond As GenericTypeParameterBuilder = typeParams(1)
Console.WriteLine("Type 'Sample' is generic: {0}", _
myType.IsGenericType)
' Apply constraints to the type parameters.
'
' A type that is substituted for the first parameter, TFirst,
' must be a reference type and must have a parameterless
' constructor.
TFirst.SetGenericParameterAttributes( _
GenericParameterAttributes.DefaultConstructorConstraint _
Or GenericParameterAttributes.ReferenceTypeConstraint)
' A type that is substituted for the second type
' parameter must implement IExampleA and IExampleB, and
' inherit from the trivial test class ExampleBase. The
' interface constraints are specified as an array
' containing the interface types.
TSecond.SetBaseTypeConstraint(baseType)
Dim interfaceTypes() As Type = {interfaceA, interfaceB}
TSecond.SetInterfaceConstraints(interfaceTypes)
' The following code adds a private field named ExampleField,
' of type TFirst.
Dim exField As FieldBuilder = _
myType.DefineField("ExampleField", TFirst, _
FieldAttributes.Private)
' Define a Shared method that takes an array of TFirst and
' returns a List(Of TFirst) containing all the elements of
' the array. To define this method it is necessary to create
' the type List(Of TFirst) by calling MakeGenericType on the
' generic type definition, List(Of T). (The T is omitted with
' the GetType operator when you get the generic type
' definition.) The parameter type is created by using the
' MakeArrayType method.
'
Dim listOf As Type = GetType(List(Of ))
Dim listOfTFirst As Type = listOf.MakeGenericType(TFirst)
Dim mParamTypes() As Type = { TFirst.MakeArrayType() }
Dim exMethod As MethodBuilder = _
myType.DefineMethod("ExampleMethod", _
MethodAttributes.Public Or MethodAttributes.Static, _
listOfTFirst, _
mParamTypes)
' Emit the method body.
' The method body consists of just three opcodes, to load
' the input array onto the execution stack, to call the
' List(Of TFirst) constructor that takes IEnumerable(Of TFirst),
' which does all the work of putting the input elements into
' the list, and to return, leaving the list on the stack. The
' hard work is getting the constructor.
'
' The GetConstructor method is not supported on a
' GenericTypeParameterBuilder, so it is not possible to get
' the constructor of List(Of TFirst) directly. There are two
' steps, first getting the constructor of List(Of T) and then
' calling a method that converts it to the corresponding
' constructor of List(Of TFirst).
'
' The constructor needed here is the one that takes an
' IEnumerable(Of T). Note, however, that this is not the
' generic type definition of IEnumerable(Of T); instead, the
' T from List(Of T) must be substituted for the T of
' IEnumerable(Of T). (This seems confusing only because both
' types have type parameters named T. That is why this example
' uses the somewhat silly names TFirst and TSecond.) To get
' the type of the constructor argument, take the generic
' type definition IEnumerable(Of T) (expressed as
' IEnumerable(Of ) when you use the GetType operator) and
' call MakeGenericType with the first generic type parameter
' of List(Of T). The constructor argument list must be passed
' as an array, with just one argument in this case.
'
' Now it is possible to get the constructor of List(Of T),
' using GetConstructor on the generic type definition. To get
' the constructor of List(Of TFirst), pass List(Of TFirst) and
' the constructor from List(Of T) to the static
' TypeBuilder.GetConstructor method.
'
Dim ilgen As ILGenerator = exMethod.GetILGenerator()
Dim ienumOf As Type = GetType(IEnumerable(Of ))
Dim listOfTParams() As Type = listOf.GetGenericArguments()
Dim TfromListOf As Type = listOfTParams(0)
Dim ienumOfT As Type = ienumOf.MakeGenericType(TfromListOf)
Dim ctorArgs() As Type = { ienumOfT }
Dim ctorPrep As ConstructorInfo = _
listOf.GetConstructor(ctorArgs)
Dim ctor As ConstructorInfo = _
TypeBuilder.GetConstructor(listOfTFirst, ctorPrep)
ilgen.Emit(OpCodes.Ldarg_0)
ilgen.Emit(OpCodes.Newobj, ctor)
ilgen.Emit(OpCodes.Ret)
' Create the type and save the assembly.
Dim finished As Type = myType.CreateType()
myAssembly.Save(myAsmName.Name & ".dll")
' Invoke the method.
' ExampleMethod is not generic, but the type it belongs to is
' generic, so in order to get a MethodInfo that can be invoked
' it is necessary to create a constructed type. The Example
' class satisfies the constraints on TFirst, because it is a
' reference type and has a default constructor. In order to
' have a class that satisfies the constraints on TSecond,
' this code example defines the ExampleDerived type. These
' two types are passed to MakeGenericMethod to create the
' constructed type.
'
Dim typeArgs() As Type = _
{ GetType(Example), GetType(ExampleDerived) }
Dim constructed As Type = finished.MakeGenericType(typeArgs)
Dim mi As MethodInfo = constructed.GetMethod("ExampleMethod")
' Create an array of Example objects, as input to the generic
' method. This array must be passed as the only element of an
' array of arguments. The first argument of Invoke is
' Nothing, because ExampleMethod is Shared. Display the count
' on the resulting List(Of Example).
'
Dim input() As Example = { New Example(), New Example() }
Dim arguments() As Object = { input }
Dim listX As List(Of Example) = mi.Invoke(Nothing, arguments)
Console.WriteLine(vbLf & _
"There are {0} elements in the List(Of Example).", _
listX.Count _
)
DisplayGenericParameters(finished)
End Sub
Private Shared Sub DisplayGenericParameters(ByVal t As Type)
If Not t.IsGenericType Then
Console.WriteLine("Type '{0}' is not generic.")
Return
End If
If Not t.IsGenericTypeDefinition Then _
t = t.GetGenericTypeDefinition()
Dim typeParameters() As Type = t.GetGenericArguments()
Console.WriteLine(vbCrLf & _
"Listing {0} type parameters for type '{1}'.", _
typeParameters.Length, t)
For Each tParam As Type In typeParameters
Console.WriteLine(vbCrLf & "Type parameter {0}:", _
tParam.ToString())
For Each c As Type In tParam.GetGenericParameterConstraints()
If c.IsInterface Then
Console.WriteLine(" Interface constraint: {0}", c)
Else
Console.WriteLine(" Base type constraint: {0}", c)
End If
Next
ListConstraintAttributes(tParam)
Next tParam
End Sub
' List the constraint flags. The GenericParameterAttributes
' enumeration contains two sets of attributes, variance and
' constraints. For this example, only constraints are used.
'
Private Shared Sub ListConstraintAttributes(ByVal t As Type)
' Mask off the constraint flags.
Dim constraints As GenericParameterAttributes = _
t.GenericParameterAttributes And _
GenericParameterAttributes.SpecialConstraintMask
If (constraints And GenericParameterAttributes.ReferenceTypeConstraint) _
<> GenericParameterAttributes.None Then _
Console.WriteLine(" ReferenceTypeConstraint")
If (constraints And GenericParameterAttributes.NotNullableValueTypeConstraint) _
<> GenericParameterAttributes.None Then _
Console.WriteLine(" NotNullableValueTypeConstraint")
If (constraints And GenericParameterAttributes.DefaultConstructorConstraint) _
<> GenericParameterAttributes.None Then _
Console.WriteLine(" DefaultConstructorConstraint")
End Sub
End Class
' This code example produces the following output:
'
'Type 'Sample' is generic: False
'Type 'Sample' is generic: True
'
'There are 2 elements in the List(Of Example).
'
'Listing 2 type parameters for type 'Sample[TFirst,TSecond]'.
'
'Type parameter TFirst:
' ReferenceTypeConstraint
' DefaultConstructorConstraint
'
'Type parameter TSecond:
' Interface constraint: IExampleA
' Interface constraint: IExampleB
' Base type constraint: ExampleBase
注解
通过使用 方法将类型参数添加到动态类型,从而使其成为泛型类型,或使用 MethodBuilder.DefineGenericParameters 方法将类型参数添加到动态方法,可以获取对象的TypeBuilder.DefineGenericParameters数组GenericTypeParameterBuilder。 GenericTypeParameterBuilder使用 对象向类型参数添加约束。 约束有三种:
基类型约束指定分配给泛型类型参数的任何类型都必须派生自特定的基类型。 使用 SetBaseTypeConstraint 方法设置此约束。
接口约束指定分配给泛型类型参数的任何类型都必须实现特定的接口。 使用 SetInterfaceConstraints 方法设置接口约束。
特殊约束指定分配给泛型类型参数的任何类型都必须具有无参数构造函数、必须是引用类型或值类型。 使用 SetGenericParameterAttributes 方法设置类型参数的特殊约束。
无法使用 类的方法 GenericTypeParameterBuilder 检索接口约束和特殊约束。 创建包含类型参数的泛型类型后,可以使用其 Type 对象来反映约束。 Type.GetGenericArguments使用 方法获取类型参数,对于每个类型参数,使用 Type.GetGenericParameterConstraints 方法获取基类型约束和接口约束,使用 Type.GenericParameterAttributes 属性获取特殊约束。
构造函数
GenericTypeParameterBuilder() |
初始化 GenericTypeParameterBuilder 类的新实例。 |
属性
Assembly |
获取 Assembly 对象,该对象表示包含当前类型参数所属的泛型类型定义的动态程序集。 |
AssemblyQualifiedName |
在所有情况下均获取 |
Attributes |
获取与 Type 关联的属性。 |
Attributes |
获取与 Type 关联的属性。 (继承自 Type) |
Attributes |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
BaseType |
获取当前泛型类型参数的基类型约束。 |
ContainsGenericParameters |
在所有情况下均获取 |
CustomAttributes |
获取包含此成员自定义属性的集合。 (继承自 MemberInfo) |
DeclaredConstructors |
获取由当前类型声明的构造函数的集合。 (继承自 TypeInfo) |
DeclaredEvents |
获取由当前类型定义的事件的集合。 (继承自 TypeInfo) |
DeclaredFields |
获取由当前类型定义的字段的集合。 (继承自 TypeInfo) |
DeclaredMembers |
获取由当前类型定义的成员的集合。 (继承自 TypeInfo) |
DeclaredMethods |
获取由当前类型定义的方法的集合。 (继承自 TypeInfo) |
DeclaredNestedTypes |
获取由当前类型定义的嵌套类型的集合。 (继承自 TypeInfo) |
DeclaredProperties |
获取由当前类型定义的属性的集合。 (继承自 TypeInfo) |
DeclaringMethod |
获取一个表示声明方法的 MethodInfo(如果当前 GenericTypeParameterBuilder 表示泛型方法的一个类型参数)。 |
DeclaringType |
获取泛型类型定义或泛型类型参数所属的泛型方法定义。 |
FullName |
在所有情况下均获取 |
GenericParameterAttributes |
获取描述当前泛型类型参数的协变和特殊约束的 GenericParameterAttributes 标志。 |
GenericParameterAttributes |
获取描述当前泛型类型参数的协变和特殊约束的 GenericParameterAttributes 标志。 (继承自 Type) |
GenericParameterPosition |
获取声明参数的泛型类型或方法的类型参数列表中的类型参数的位置。 |
GenericTypeArguments |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 |
GenericTypeArguments |
获取此类型泛型类型参数的数组。 (继承自 Type) |
GenericTypeArguments |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
GenericTypeParameters |
获取当前实例泛型类型参数的数组。 (继承自 TypeInfo) |
GUID |
不支持不完整的泛型类型参数。 |
HasElementType |
获取一个值,通过该值指示当前 Type 是包含还是引用另一类型,即当前 Type 是数组、指针还是通过引用传递。 (继承自 Type) |
HasElementType |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
ImplementedInterfaces |
获取当前类型实现的接口的集合。 (继承自 TypeInfo) |
IsAbstract |
获取一个值,通过该值指示 Type 是否为抽象的并且必须被重写。 (继承自 Type) |
IsAbstract |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsAnsiClass |
获取一个值,该值指示是否为 |
IsAnsiClass |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsArray |
获取一个值,该值指示类型是否为数组。 (继承自 Type) |
IsArray |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsAutoClass |
获取一个值,该值指示是否为 |
IsAutoClass |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsAutoLayout |
获取指示当前类型的字段是否由公共语言运行时自动放置的值。 (继承自 Type) |
IsAutoLayout |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsByRef |
获取一个值,该值指示 Type 是否由引用传递。 (继承自 Type) |
IsByRef |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsByRefLike |
获取一个值,该值指示类型是否是与 byref 类似的结构。 |
IsByRefLike |
获取一个值,该值指示类型是否是与 byref 类似的结构。 (继承自 Type) |
IsClass |
获取一个值,通过该值指示 Type 是否是一个类或委托;即,不是值类型或接口。 (继承自 Type) |
IsClass |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsCollectible |
获取一个值,该值指示此 MemberInfo 对象是否是包含在可回收的 AssemblyLoadContext 中的程序集的一部分。 (继承自 MemberInfo) |
IsCOMObject |
获取一个值,通过该值指示 Type 是否为 COM 对象。 (继承自 Type) |
IsCOMObject |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsConstructedGenericType |
获取指示此对象是否表示构造的泛型类型的值。 |
IsConstructedGenericType |
获取指示此对象是否表示构造的泛型类型的值。 你可以创建构造型泛型类型的实例。 (继承自 Type) |
IsContextful |
获取一个值,通过该值指示 Type 在上下文中是否可以被承载。 (继承自 Type) |
IsEnum |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 |
IsEnum |
获取一个值,该值指示当前的 Type 是否表示枚举。 (继承自 Type) |
IsEnum |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsExplicitLayout |
获取指示当前类型的字段是否放置在显式指定的偏移量处的值。 (继承自 Type) |
IsExplicitLayout |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsFunctionPointer |
获取一个值,该值指示当前 Type 是否为函数指针。 (继承自 Type) |
IsGenericMethodParameter |
获取一个值,该值指示当前 Type 是否表示泛型方法定义中的类型参数。 (继承自 Type) |
IsGenericParameter |
在所有情况下均获取 |
IsGenericType |
在所有情况下均返回 |
IsGenericTypeDefinition |
在所有情况下均获取 |
IsGenericTypeParameter |
获取一个值,该值指示当前 Type 是否表示泛型类型定义中的类型参数。 (继承自 Type) |
IsImport |
获取一个值,该值指示 Type 是否应用了 ComImportAttribute 属性,如果应用了该属性,则表示它是从 COM 类型库导入的。 (继承自 Type) |
IsImport |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsInterface |
获取一个值,通过该值指示 Type 是否是一个接口;即,不是类或值类型。 (继承自 Type) |
IsInterface |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsLayoutSequential |
获取指示当前类型的字段是否按顺序(定义顺序或发送到元数据的顺序)放置的值。 (继承自 Type) |
IsLayoutSequential |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsMarshalByRef |
获取一个值,该值指示 Type 是否按引用进行封送。 (继承自 Type) |
IsMarshalByRef |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNested |
获取一个指示当前 Type 对象是否表示其定义嵌套在另一个类型的定义之内的类型的值。 (继承自 Type) |
IsNested |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedAssembly |
获取一个值,通过该值指示 Type 是否是嵌套的并且只能在它自己的程序集内可见。 (继承自 Type) |
IsNestedAssembly |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedFamANDAssem |
获取一个值,通过该值指示 Type 是否是嵌套的并且只对同时属于自己家族和自己程序集的类可见。 (继承自 Type) |
IsNestedFamANDAssem |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedFamily |
获取一个值,通过该值指示 Type 是否是嵌套的并且只能在它自己的家族内可见。 (继承自 Type) |
IsNestedFamily |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedFamORAssem |
获取一个值,通过该值指示 Type 是否是嵌套的并且只对属于它自己的家族或属于它自己的程序集的类可见。 (继承自 Type) |
IsNestedFamORAssem |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedPrivate |
获取一个值,通过该值指示 Type 是否是嵌套的并声明为私有。 (继承自 Type) |
IsNestedPrivate |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNestedPublic |
获取一个值,通过该值指示类是否是嵌套的并且声明为公共的。 (继承自 Type) |
IsNestedPublic |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsNotPublic |
获取一个值,该值指示 Type 是否声明为公共类型。 (继承自 Type) |
IsNotPublic |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsPointer |
获取一个值,通过该值指示 Type 是否为指针。 (继承自 Type) |
IsPointer |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsPrimitive |
获取一个值,通过该值指示 Type 是否为基元类型之一。 (继承自 Type) |
IsPrimitive |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsPublic |
获取一个值,该值指示 Type 是否声明为公共类型。 (继承自 Type) |
IsPublic |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsSealed |
获取一个值,该值指示 Type 是否声明为密封的。 (继承自 Type) |
IsSealed |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsSecurityCritical |
获取一个值,该值指示当前的类型在当前信任级别上是安全关键的还是安全可靠关键的,并因此可以执行关键操作。 (继承自 Type) |
IsSecuritySafeCritical |
获取一个值,该值指示当前类型在当前信任级别上是否是安全可靠关键的;即它是否可以执行关键操作并可以由透明代码访问。 (继承自 Type) |
IsSecurityTransparent |
获取一个值,该值指示当前类型在当前信任级别上是否是透明的而无法执行关键操作。 (继承自 Type) |
IsSerializable |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 |
IsSerializable |
已过时.
获取一个值, Type 该值指示 是否可序列化二进制。 (继承自 Type) |
IsSerializable |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsSignatureType |
获取一个值,该值指示类型是否是签名类型。 (继承自 Type) |
IsSpecialName |
获取一个值,该值指示该类型是否具有需要特殊处理的名称。 (继承自 Type) |
IsSpecialName |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsSZArray |
获取一个值,该值指示类型是否是仅可表示下限为零的一维数组的数组类型。 |
IsSZArray |
获取一个值,该值指示类型是否是仅可表示下限为零的一维数组的数组类型。 (继承自 Type) |
IsTypeDefinition |
获取一个值,该值指示类型是否是类型定义。 |
IsTypeDefinition |
获取一个值,该值指示类型是否是类型定义。 (继承自 Type) |
IsUnicodeClass |
获取一个值,该值指示是否为 |
IsUnicodeClass |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsUnmanagedFunctionPointer |
获取一个值,该值指示当前 Type 是否为非托管函数指针。 (继承自 Type) |
IsValueType |
获取一个值,通过该值指示 Type 是否为值类型。 (继承自 Type) |
IsValueType |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
IsVariableBoundArray |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 |
IsVariableBoundArray |
获取一个值,该值指示类型是否是可表示多维数组或具有任意下限的数组的数组类型。 (继承自 Type) |
IsVisible |
获取一个指示 Type 是否可由程序集之外的代码访问的值。 (继承自 Type) |
IsVisible |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
MemberType |
获取一个指示此成员是类型还是嵌套类型的 MemberTypes 值。 (继承自 Type) |
MemberType |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
MetadataToken |
获取一个标记,该标记用于标识元数据中的当前动态模块。 |
MetadataToken |
获取一个值,该值标识元数据元素。 (继承自 MemberInfo) |
Module |
获取包含泛型类型参数的动态模块。 |
Name |
获取泛型类型参数的名称。 |
Namespace |
在所有情况下均获取 |
ReflectedType |
获取用于获取 GenericTypeParameterBuilder 的 Type 对象。 |
ReflectedType |
获取用于获取 |
StructLayoutAttribute |
获取一个描述当前类型的布局的 StructLayoutAttribute。 (继承自 Type) |
StructLayoutAttribute |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
TypeHandle |
不支持不完整的泛型类型参数。 |
TypeInitializer |
获取该类型的初始值设定项。 (继承自 Type) |
TypeInitializer |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |
UnderlyingSystemType |
获取当前泛型类型参数。 |
UnderlyingSystemType |
为动态定义的泛型类型和方法定义并创建泛型类型参数。 此类不能被继承。 (继承自 TypeInfo) |