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 |
取得表示目前類型的欄位是否已由 Common Language Runtime 自動配置版面的值。 (繼承來源 Type) |
IsAutoLayout |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
IsByRef |
取得值,指出 Type 是否以傳址方式傳遞。 (繼承來源 Type) |
IsByRef |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
IsByRefLike |
取得值,指出類型是否為 byref-like 結構。 |
IsByRefLike |
取得值,指出類型是否為 byref-like 結構。 (繼承來源 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 屬性 (Attribute),亦即其是否從 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 |
取得值,指出類別是否為巢狀 (Nest) 並且宣告為公用 (Public)。 (繼承來源 Type) |
IsNestedPublic |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
IsNotPublic |
取得值,指出 Type 是否未宣告為公用。 (繼承來源 Type) |
IsNotPublic |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
IsPointer |
取得值,指出 Type 是否為指標。 (繼承來源 Type) |
IsPointer |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
IsPrimitive |
取得值,指出 Type 是否為其中一個基本類型 (Primitive 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 是否為 Unmanaged 函式指標。 (繼承來源 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 |
取得 Type 物件,用來取得 GenericTypeParameterBuilder。 |
ReflectedType |
取得類別物件,是用來取得這個 |
StructLayoutAttribute |
取得描述目前類型配置的 StructLayoutAttribute。 (繼承來源 Type) |
StructLayoutAttribute |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
TypeHandle |
不支援不完整的泛型型別參數。 |
TypeInitializer |
取得類型的初始設定式。 (繼承來源 Type) |
TypeInitializer |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |
UnderlyingSystemType |
取得目前的泛型型別參數。 |
UnderlyingSystemType |
定義和建立動態定義泛型類型和方法的泛型型別參數。 此類別無法獲得繼承。 (繼承來源 TypeInfo) |