Bewerken

Delen via


GenericTypeParameterBuilder Class

Definition

Defines and creates generic type parameters for dynamically defined generic types and methods. This class cannot be inherited.

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
Inheritance
GenericTypeParameterBuilder
Inheritance
GenericTypeParameterBuilder
Inheritance
GenericTypeParameterBuilder
Inheritance
GenericTypeParameterBuilder
Attributes

Examples

The following code example creates a generic type with two type parameters, and saves them in the assembly GenericEmitExample1.dll. You can use the Ildasm.exe (IL Disassembler) to view the generated types. For a more detailed explanation of the steps involved in defining a dynamic generic type, see How to: Define a Generic Type with Reflection Emit.

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

Remarks

You can get an array of GenericTypeParameterBuilder objects by using the TypeBuilder.DefineGenericParameters method to add type parameters to a dynamic type, thus making it a generic type, or by using the MethodBuilder.DefineGenericParameters method to add type parameters to a dynamic method. Use the GenericTypeParameterBuilder objects to add constraints to the type parameters. Constraints are of three kinds:

  • The base type constraint specifies that any type assigned to the generic type parameter must derive from a particular base type. Set this constraint by using the SetBaseTypeConstraint method.

  • An interface constraint specifies that any type assigned to the generic type parameter must implement a particular interface. Set the interface constraints by using the SetInterfaceConstraints method.

  • Special constraints specify that any type assigned to the generic type parameter must have a parameterless constructor, must be a reference type, or must be a value type. Set the special constraints for a type parameter by using the SetGenericParameterAttributes method.

Interface constraints and special constraints cannot be retrieved using methods of the GenericTypeParameterBuilder class. Once you have created the generic type that contains the type parameters, you can use its Type object to reflect the constraints. Use the Type.GetGenericArguments method to get the type parameters, and for each type parameter use the Type.GetGenericParameterConstraints method to get the base type constraint and interface constraints, and the Type.GenericParameterAttributes property to get the special constraints.

Constructors

GenericTypeParameterBuilder()

Initializes a new instance of GenericTypeParameterBuilder class.

Properties

Assembly

Gets an Assembly object representing the dynamic assembly that contains the generic type definition the current type parameter belongs to.

AssemblyQualifiedName

Gets null in all cases.

Attributes

Gets the attributes associated with the Type.

Attributes

Gets the attributes associated with the Type.

(Inherited from Type)
Attributes (Inherited from TypeInfo)
BaseType

Gets the base type constraint of the current generic type parameter.

ContainsGenericParameters

Gets true in all cases.

CustomAttributes

Gets a collection that contains this member's custom attributes.

(Inherited from MemberInfo)
DeclaredConstructors

Gets a collection of the constructors declared by the current type.

(Inherited from TypeInfo)
DeclaredEvents

Gets a collection of the events defined by the current type.

(Inherited from TypeInfo)
DeclaredFields

Gets a collection of the fields defined by the current type.

(Inherited from TypeInfo)
DeclaredMembers

Gets a collection of the members defined by the current type.

(Inherited from TypeInfo)
DeclaredMethods

Gets a collection of the methods defined by the current type.

(Inherited from TypeInfo)
DeclaredNestedTypes

Gets a collection of the nested types defined by the current type.

(Inherited from TypeInfo)
DeclaredProperties

Gets a collection of the properties defined by the current type.

(Inherited from TypeInfo)
DeclaringMethod

Gets a MethodInfo that represents the declaring method, if the current GenericTypeParameterBuilder represents a type parameter of a generic method.

DeclaringType

Gets the generic type definition or generic method definition to which the generic type parameter belongs.

FullName

Gets null in all cases.

GenericParameterAttributes

Gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current generic type parameter.

GenericParameterAttributes

Gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current generic type parameter.

(Inherited from Type)
GenericParameterPosition

Gets the position of the type parameter in the type parameter list of the generic type or method that declared the parameter.

GenericTypeArguments
GenericTypeArguments

Gets an array of the generic type arguments for this type.

(Inherited from Type)
GenericTypeArguments (Inherited from TypeInfo)
GenericTypeParameters

Gets an array of the generic type parameters of the current instance.

(Inherited from TypeInfo)
GUID

Not supported for incomplete generic type parameters.

HasElementType

Gets a value indicating whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference.

(Inherited from Type)
HasElementType (Inherited from TypeInfo)
ImplementedInterfaces

Gets a collection of the interfaces implemented by the current type.

(Inherited from TypeInfo)
IsAbstract

Gets a value indicating whether the Type is abstract and must be overridden.

(Inherited from Type)
IsAbstract (Inherited from TypeInfo)
IsAnsiClass

Gets a value indicating whether the string format attribute AnsiClass is selected for the Type.

(Inherited from Type)
IsAnsiClass (Inherited from TypeInfo)
IsArray

Gets a value that indicates whether the type is an array.

(Inherited from Type)
IsArray (Inherited from TypeInfo)
IsAutoClass

Gets a value indicating whether the string format attribute AutoClass is selected for the Type.

(Inherited from Type)
IsAutoClass (Inherited from TypeInfo)
IsAutoLayout

Gets a value indicating whether the fields of the current type are laid out automatically by the common language runtime.

(Inherited from Type)
IsAutoLayout (Inherited from TypeInfo)
IsByRef

Gets a value indicating whether the Type is passed by reference.

(Inherited from Type)
IsByRef (Inherited from TypeInfo)
IsByRefLike

Gets a value that indicates whether the type is a byref-like structure.

IsByRefLike

Gets a value that indicates whether the type is a byref-like structure.

(Inherited from Type)
IsClass

Gets a value indicating whether the Type is a class or a delegate; that is, not a value type or interface.

(Inherited from Type)
IsClass (Inherited from TypeInfo)
IsCollectible

Gets a value that indicates whether this MemberInfo object is part of an assembly held in a collectible AssemblyLoadContext.

(Inherited from MemberInfo)
IsCOMObject

Gets a value indicating whether the Type is a COM object.

(Inherited from Type)
IsCOMObject (Inherited from TypeInfo)
IsConstructedGenericType

Gets a value that indicates whether this object represents a constructed generic type.

IsConstructedGenericType

Gets a value that indicates whether this object represents a constructed generic type. You can create instances of a constructed generic type.

(Inherited from Type)
IsContextful

Gets a value indicating whether the Type can be hosted in a context.

(Inherited from Type)
IsEnum
IsEnum

Gets a value indicating whether the current Type represents an enumeration.

(Inherited from Type)
IsEnum (Inherited from TypeInfo)
IsExplicitLayout

Gets a value indicating whether the fields of the current type are laid out at explicitly specified offsets.

(Inherited from Type)
IsExplicitLayout (Inherited from TypeInfo)
IsFunctionPointer

Gets a value that indicates whether the current Type is a function pointer.

(Inherited from Type)
IsGenericMethodParameter

Gets a value that indicates whether the current Type represents a type parameter in the definition of a generic method.

(Inherited from Type)
IsGenericParameter

Gets true in all cases.

IsGenericType

Returns false in all cases.

IsGenericTypeDefinition

Gets false in all cases.

IsGenericTypeParameter

Gets a value that indicates whether the current Type represents a type parameter in the definition of a generic type.

(Inherited from Type)
IsImport

Gets a value indicating whether the Type has a ComImportAttribute attribute applied, indicating that it was imported from a COM type library.

(Inherited from Type)
IsImport (Inherited from TypeInfo)
IsInterface

Gets a value indicating whether the Type is an interface; that is, not a class or a value type.

(Inherited from Type)
IsInterface (Inherited from TypeInfo)
IsLayoutSequential

Gets a value indicating whether the fields of the current type are laid out sequentially, in the order that they were defined or emitted to the metadata.

(Inherited from Type)
IsLayoutSequential (Inherited from TypeInfo)
IsMarshalByRef

Gets a value indicating whether the Type is marshaled by reference.

(Inherited from Type)
IsMarshalByRef (Inherited from TypeInfo)
IsNested

Gets a value indicating whether the current Type object represents a type whose definition is nested inside the definition of another type.

(Inherited from Type)
IsNested (Inherited from TypeInfo)
IsNestedAssembly

Gets a value indicating whether the Type is nested and visible only within its own assembly.

(Inherited from Type)
IsNestedAssembly (Inherited from TypeInfo)
IsNestedFamANDAssem

Gets a value indicating whether the Type is nested and visible only to classes that belong to both its own family and its own assembly.

(Inherited from Type)
IsNestedFamANDAssem (Inherited from TypeInfo)
IsNestedFamily

Gets a value indicating whether the Type is nested and visible only within its own family.

(Inherited from Type)
IsNestedFamily (Inherited from TypeInfo)
IsNestedFamORAssem

Gets a value indicating whether the Type is nested and visible only to classes that belong to either its own family or to its own assembly.

(Inherited from Type)
IsNestedFamORAssem (Inherited from TypeInfo)
IsNestedPrivate

Gets a value indicating whether the Type is nested and declared private.

(Inherited from Type)
IsNestedPrivate (Inherited from TypeInfo)
IsNestedPublic

Gets a value indicating whether a class is nested and declared public.

(Inherited from Type)
IsNestedPublic (Inherited from TypeInfo)
IsNotPublic

Gets a value indicating whether the Type is not declared public.

(Inherited from Type)
IsNotPublic (Inherited from TypeInfo)
IsPointer

Gets a value indicating whether the Type is a pointer.

(Inherited from Type)
IsPointer (Inherited from TypeInfo)
IsPrimitive

Gets a value indicating whether the Type is one of the primitive types.

(Inherited from Type)
IsPrimitive (Inherited from TypeInfo)
IsPublic

Gets a value indicating whether the Type is declared public.

(Inherited from Type)
IsPublic (Inherited from TypeInfo)
IsSealed

Gets a value indicating whether the Type is declared sealed.

(Inherited from Type)
IsSealed (Inherited from TypeInfo)
IsSecurityCritical

Gets a value that indicates whether the current type is security-critical or security-safe-critical at the current trust level, and therefore can perform critical operations.

(Inherited from Type)
IsSecuritySafeCritical

Gets a value that indicates whether the current type is security-safe-critical at the current trust level; that is, whether it can perform critical operations and can be accessed by transparent code.

(Inherited from Type)
IsSecurityTransparent

Gets a value that indicates whether the current type is transparent at the current trust level, and therefore cannot perform critical operations.

(Inherited from Type)
IsSerializable
IsSerializable
Obsolete.

Gets a value indicating whether the Type is binary serializable.

(Inherited from Type)
IsSerializable (Inherited from TypeInfo)
IsSignatureType

Gets a value that indicates whether the type is a signature type.

(Inherited from Type)
IsSpecialName

Gets a value indicating whether the type has a name that requires special handling.

(Inherited from Type)
IsSpecialName (Inherited from TypeInfo)
IsSZArray

Gets a value that indicates whether the type is an array type that can represent only a single-dimensional array with a zero lower bound.

IsSZArray

Gets a value that indicates whether the type is an array type that can represent only a single-dimensional array with a zero lower bound.

(Inherited from Type)
IsTypeDefinition

Gets a value that indicates whether the type is a type definition.

IsTypeDefinition

Gets a value that indicates whether the type is a type definition.

(Inherited from Type)
IsUnicodeClass

Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type.

(Inherited from Type)
IsUnicodeClass (Inherited from TypeInfo)
IsUnmanagedFunctionPointer

Gets a value that indicates whether the current Type is an unmanaged function pointer.

(Inherited from Type)
IsValueType

Gets a value indicating whether the Type is a value type.

(Inherited from Type)
IsValueType (Inherited from TypeInfo)
IsVariableBoundArray
IsVariableBoundArray

Gets a value that indicates whether the type is an array type that can represent a multi-dimensional array or an array with an arbitrary lower bound.

(Inherited from Type)
IsVisible

Gets a value indicating whether the Type can be accessed by code outside the assembly.

(Inherited from Type)
IsVisible (Inherited from TypeInfo)
MemberType

Gets a MemberTypes value indicating that this member is a type or a nested type.

(Inherited from Type)
MemberType (Inherited from TypeInfo)
MetadataToken

Gets a token that identifies the current dynamic module in metadata.

MetadataToken

Gets a value that identifies a metadata element.

(Inherited from MemberInfo)
Module

Gets the dynamic module that contains the generic type parameter.

Name

Gets the name of the generic type parameter.

Namespace

Gets null in all cases.

ReflectedType

Gets the Type object that was used to obtain the GenericTypeParameterBuilder.

ReflectedType

Gets the class object that was used to obtain this instance of MemberInfo.

(Inherited from MemberInfo)
StructLayoutAttribute

Gets a StructLayoutAttribute that describes the layout of the current type.

(Inherited from Type)
StructLayoutAttribute (Inherited from TypeInfo)
TypeHandle

Not supported for incomplete generic type parameters.

TypeInitializer

Gets the initializer for the type.

(Inherited from Type)
TypeInitializer (Inherited from TypeInfo)
UnderlyingSystemType

Gets the current generic type parameter.

UnderlyingSystemType (Inherited from TypeInfo)

Methods

AsType()

Returns the current type as a Type object.

(Inherited from TypeInfo)
Equals(Object)

Tests whether the given object is an instance of EventToken and is equal to the current instance.

Equals(Type)

Determines if the underlying system type of the current Type is the same as the underlying system type of the specified Type.

(Inherited from Type)
FindInterfaces(TypeFilter, Object)

Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type.

(Inherited from Type)
FindInterfaces(TypeFilter, Object) (Inherited from TypeInfo)
FindMembers(MemberTypes, BindingFlags, MemberFilter, Object)

Returns a filtered array of MemberInfo objects of the specified member type.

(Inherited from Type)
FindMembers(MemberTypes, BindingFlags, MemberFilter, Object) (Inherited from TypeInfo)
GetArrayRank()
GetArrayRank()

Gets the number of dimensions in an array.

(Inherited from Type)
GetArrayRank() (Inherited from TypeInfo)
GetAttributeFlagsImpl()

When overridden in a derived class, implements the Attributes property and gets a bitwise combination of enumeration values that indicate the attributes associated with the Type.

GetAttributeFlagsImpl()

When overridden in a derived class, implements the Attributes property and gets a bitwise combination of enumeration values that indicate the attributes associated with the Type.

(Inherited from Type)
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])

Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetConstructor(BindingFlags, Type[])

Searches for a constructor whose parameters match the specified argument types, using the specified binding constraints.

(Inherited from Type)
GetConstructor(Type[])

Searches for a public instance constructor whose parameters match the types in the specified array.

(Inherited from Type)
GetConstructor(Type[]) (Inherited from TypeInfo)
GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Not supported for incomplete generic type parameters.

GetConstructorImpl(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

When overridden in a derived class, searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetConstructors()

Returns all the public constructors defined for the current Type.

(Inherited from Type)
GetConstructors() (Inherited from TypeInfo)
GetConstructors(BindingFlags)

Not supported for incomplete generic type parameters.

GetConstructors(BindingFlags) (Inherited from TypeInfo)
GetCustomAttributes(Boolean)

Not supported for incomplete generic type parameters.

GetCustomAttributes(Boolean)

When overridden in a derived class, returns an array of all custom attributes applied to this member.

(Inherited from MemberInfo)
GetCustomAttributes(Type, Boolean)

Not supported for incomplete generic type parameters.

GetCustomAttributes(Type, Boolean)

When overridden in a derived class, returns an array of custom attributes applied to this member and identified by Type.

(Inherited from MemberInfo)
GetCustomAttributesData()

Returns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member.

(Inherited from MemberInfo)
GetDeclaredEvent(String)

Returns an object that represents the specified event declared by the current type.

(Inherited from TypeInfo)
GetDeclaredField(String)

Returns an object that represents the specified field declared by the current type.

(Inherited from TypeInfo)
GetDeclaredMethod(String)

Returns an object that represents the specified method declared by the current type.

(Inherited from TypeInfo)
GetDeclaredMethods(String)

Returns a collection that contains all methods declared on the current type that match the specified name.

(Inherited from TypeInfo)
GetDeclaredNestedType(String)

Returns an object that represents the specified nested type declared by the current type.

(Inherited from TypeInfo)
GetDeclaredProperty(String)

Returns an object that represents the specified property declared by the current type.

(Inherited from TypeInfo)
GetDefaultMembers()

Searches for the members defined for the current Type whose DefaultMemberAttribute is set.

(Inherited from Type)
GetDefaultMembers() (Inherited from TypeInfo)
GetElementType()

Throws a NotSupportedException in all cases.

GetEnumName(Object)

Returns the name of the constant that has the specified value, for the current enumeration type.

(Inherited from Type)
GetEnumName(Object) (Inherited from TypeInfo)
GetEnumNames()

Returns the names of the members of the current enumeration type.

(Inherited from Type)
GetEnumNames() (Inherited from TypeInfo)
GetEnumUnderlyingType()

Returns the underlying type of the current enumeration type.

(Inherited from Type)
GetEnumUnderlyingType() (Inherited from TypeInfo)
GetEnumValues()

Returns an array of the values of the constants in the current enumeration type.

(Inherited from Type)
GetEnumValues() (Inherited from TypeInfo)
GetEnumValuesAsUnderlyingType()

Retrieves an array of the values of the underlying type constants of this enumeration type.

(Inherited from Type)
GetEvent(String, BindingFlags)

Not supported for incomplete generic type parameters.

GetEvent(String, BindingFlags) (Inherited from TypeInfo)
GetEvent(String)

Returns the EventInfo object representing the specified public event.

(Inherited from Type)
GetEvent(String) (Inherited from TypeInfo)
GetEvents()

Not supported for incomplete generic type parameters.

GetEvents() (Inherited from TypeInfo)
GetEvents(BindingFlags)

Not supported for incomplete generic type parameters.

GetEvents(BindingFlags) (Inherited from TypeInfo)
GetField(String, BindingFlags)

Not supported for incomplete generic type parameters.

GetField(String, BindingFlags) (Inherited from TypeInfo)
GetField(String)

Searches for the public field with the specified name.

(Inherited from Type)
GetField(String) (Inherited from TypeInfo)
GetFields()

Returns all the public fields of the current Type.

(Inherited from Type)
GetFields() (Inherited from TypeInfo)
GetFields(BindingFlags)

Not supported for incomplete generic type parameters.

GetFields(BindingFlags) (Inherited from TypeInfo)
GetFunctionPointerCallingConventions()

When overridden in a derived class, returns the calling conventions of the current function pointer Type.

(Inherited from Type)
GetFunctionPointerParameterTypes()

When overridden in a derived class, returns the parameter types of the current function pointer Type.

(Inherited from Type)
GetFunctionPointerReturnType()

When overridden in a derived class, returns the return type of the current function pointer Type.

(Inherited from Type)
GetGenericArguments()

Not valid for generic type parameters.

GetGenericArguments() (Inherited from TypeInfo)
GetGenericParameterConstraints()
GetGenericParameterConstraints()

Returns an array of Type objects that represent the constraints on the current generic type parameter.

(Inherited from Type)
GetGenericParameterConstraints() (Inherited from TypeInfo)
GetGenericTypeDefinition()

Not valid for generic type parameters.

GetHashCode()

Returns a 32-bit integer hash code for the current instance.

GetInterface(String, Boolean)

Not supported for incomplete generic type parameters.

GetInterface(String, Boolean) (Inherited from TypeInfo)
GetInterface(String)

Searches for the interface with the specified name.

(Inherited from Type)
GetInterface(String) (Inherited from TypeInfo)
GetInterfaceMap(Type)

Not supported for incomplete generic type parameters.

GetInterfaces()

Not supported for incomplete generic type parameters.

GetInterfaces() (Inherited from TypeInfo)
GetMember(String, BindingFlags)

Searches for the specified members, using the specified binding constraints.

(Inherited from Type)
GetMember(String, BindingFlags) (Inherited from TypeInfo)
GetMember(String, MemberTypes, BindingFlags)

Not supported for incomplete generic type parameters.

GetMember(String, MemberTypes, BindingFlags) (Inherited from TypeInfo)
GetMember(String)

Searches for the public members with the specified name.

(Inherited from Type)
GetMember(String) (Inherited from TypeInfo)
GetMembers()

Returns all the public members of the current Type.

(Inherited from Type)
GetMembers() (Inherited from TypeInfo)
GetMembers(BindingFlags)

Not supported for incomplete generic type parameters.

GetMembers(BindingFlags) (Inherited from TypeInfo)
GetMemberWithSameMetadataDefinitionAs(MemberInfo)

Searches for the MemberInfo on the current Type that matches the specified MemberInfo.

(Inherited from Type)
GetMethod(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetMethod(String, BindingFlags, Type[])

Searches for the specified method whose parameters match the specified argument types, using the specified binding constraints.

(Inherited from Type)
GetMethod(String, BindingFlags)

Searches for the specified method, using the specified binding constraints.

(Inherited from Type)
GetMethod(String, BindingFlags) (Inherited from TypeInfo)
GetMethod(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetMethod(String, Int32, BindingFlags, Binder, Type[], ParameterModifier[])

Searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetMethod(String, Int32, BindingFlags, Type[])

Searches for the specified method whose parameters match the specified generic parameter count and argument types, using the specified binding constraints.

(Inherited from Type)
GetMethod(String, Int32, Type[], ParameterModifier[])

Searches for the specified public method whose parameters match the specified generic parameter count, argument types and modifiers.

(Inherited from Type)
GetMethod(String, Int32, Type[])

Searches for the specified public method whose parameters match the specified generic parameter count and argument types.

(Inherited from Type)
GetMethod(String, Type[], ParameterModifier[])

Searches for the specified public method whose parameters match the specified argument types and modifiers.

(Inherited from Type)
GetMethod(String, Type[], ParameterModifier[]) (Inherited from TypeInfo)
GetMethod(String, Type[])

Searches for the specified public method whose parameters match the specified argument types.

(Inherited from Type)
GetMethod(String, Type[]) (Inherited from TypeInfo)
GetMethod(String)

Searches for the public method with the specified name.

(Inherited from Type)
GetMethod(String) (Inherited from TypeInfo)
GetMethodImpl(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Not supported for incomplete generic type parameters.

GetMethodImpl(String, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

When overridden in a derived class, searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

When overridden in a derived class, searches for the specified method whose parameters match the specified generic parameter count, argument types and modifiers, using the specified binding constraints and the specified calling convention.

(Inherited from Type)
GetMethods()

Returns all the public methods of the current Type.

(Inherited from Type)
GetMethods() (Inherited from TypeInfo)
GetMethods(BindingFlags)

Not supported for incomplete generic type parameters.

GetMethods(BindingFlags) (Inherited from TypeInfo)
GetNestedType(String, BindingFlags)

Not supported for incomplete generic type parameters.

GetNestedType(String, BindingFlags) (Inherited from TypeInfo)
GetNestedType(String)

Searches for the public nested type with the specified name.

(Inherited from Type)
GetNestedType(String) (Inherited from TypeInfo)
GetNestedTypes()

Returns the public types nested in the current Type.

(Inherited from Type)
GetNestedTypes() (Inherited from TypeInfo)
GetNestedTypes(BindingFlags)

Not supported for incomplete generic type parameters.

GetNestedTypes(BindingFlags) (Inherited from TypeInfo)
GetOptionalCustomModifiers()

When overridden in a derived class, returns the optional custom modifiers of the current Type.

(Inherited from Type)
GetProperties()

Returns all the public properties of the current Type.

(Inherited from Type)
GetProperties() (Inherited from TypeInfo)
GetProperties(BindingFlags)

Not supported for incomplete generic type parameters.

GetProperties(BindingFlags) (Inherited from TypeInfo)
GetProperty(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetProperty(String, BindingFlags)

Searches for the specified property, using the specified binding constraints.

(Inherited from Type)
GetProperty(String, BindingFlags) (Inherited from TypeInfo)
GetProperty(String, Type, Type[], ParameterModifier[])

Searches for the specified public property whose parameters match the specified argument types and modifiers.

(Inherited from Type)
GetProperty(String, Type, Type[], ParameterModifier[]) (Inherited from TypeInfo)
GetProperty(String, Type, Type[])

Searches for the specified public property whose parameters match the specified argument types.

(Inherited from Type)
GetProperty(String, Type, Type[]) (Inherited from TypeInfo)
GetProperty(String, Type)

Searches for the public property with the specified name and return type.

(Inherited from Type)
GetProperty(String, Type) (Inherited from TypeInfo)
GetProperty(String, Type[])

Searches for the specified public property whose parameters match the specified argument types.

(Inherited from Type)
GetProperty(String, Type[]) (Inherited from TypeInfo)
GetProperty(String)

Searches for the public property with the specified name.

(Inherited from Type)
GetProperty(String) (Inherited from TypeInfo)
GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

Not supported for incomplete generic type parameters.

GetPropertyImpl(String, BindingFlags, Binder, Type, Type[], ParameterModifier[])

When overridden in a derived class, searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetRequiredCustomModifiers()

When overridden in a derived class, returns the required custom modifiers of the current Type.

(Inherited from Type)
GetType()

Gets the current Type.

(Inherited from Type)
GetType()

Discovers the attributes of a member and provides access to member metadata.

(Inherited from MemberInfo)
GetTypeCodeImpl()

Returns the underlying type code of this Type instance.

(Inherited from Type)
HasElementTypeImpl()

When overridden in a derived class, implements the HasElementType property and determines whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference.

HasElementTypeImpl()

When overridden in a derived class, implements the HasElementType property and determines whether the current Type encompasses or refers to another type; that is, whether the current Type is an array, a pointer, or is passed by reference.

(Inherited from Type)
HasSameMetadataDefinitionAs(MemberInfo) (Inherited from MemberInfo)
InvokeMember(String, BindingFlags, Binder, Object, Object[], CultureInfo)

Invokes the specified member, using the specified binding constraints and matching the specified argument list and culture.

(Inherited from Type)
InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

Not supported for incomplete generic type parameters.

InvokeMember(String, BindingFlags, Binder, Object, Object[])

Invokes the specified member, using the specified binding constraints and matching the specified argument list.

(Inherited from Type)
IsArrayImpl()

When overridden in a derived class, implements the IsArray property and determines whether the Type is an array.

IsArrayImpl()

When overridden in a derived class, implements the IsArray property and determines whether the Type is an array.

(Inherited from Type)
IsAssignableFrom(Type)

Throws a NotSupportedException exception in all cases.

IsAssignableFrom(Type) (Inherited from TypeInfo)
IsAssignableFrom(TypeInfo)

Throws a NotSupportedException exception in all cases.

IsAssignableTo(Type)

Determines whether the current type can be assigned to a variable of the specified targetType.

(Inherited from Type)
IsByRefImpl()

When overridden in a derived class, implements the IsByRef property and determines whether the Type is passed by reference.

IsByRefImpl()

When overridden in a derived class, implements the IsByRef property and determines whether the Type is passed by reference.

(Inherited from Type)
IsCOMObjectImpl()

When overridden in a derived class, implements the IsCOMObject property and determines whether the Type is a COM object.

IsCOMObjectImpl()

When overridden in a derived class, implements the IsCOMObject property and determines whether the Type is a COM object.

(Inherited from Type)
IsContextfulImpl()

Implements the IsContextful property and determines whether the Type can be hosted in a context.

(Inherited from Type)
IsDefined(Type, Boolean)

Not supported for incomplete generic type parameters.

IsDefined(Type, Boolean)

When overridden in a derived class, indicates whether one or more attributes of the specified type or of its derived types is applied to this member.

(Inherited from MemberInfo)
IsEnumDefined(Object)

Returns a value that indicates whether the specified value exists in the current enumeration type.

(Inherited from Type)
IsEnumDefined(Object) (Inherited from TypeInfo)
IsEquivalentTo(Type)

Determines whether two COM types have the same identity and are eligible for type equivalence.

(Inherited from Type)
IsEquivalentTo(Type) (Inherited from TypeInfo)
IsInstanceOfType(Object)

Determines whether the specified object is an instance of the current Type.

(Inherited from Type)
IsInstanceOfType(Object) (Inherited from TypeInfo)
IsMarshalByRefImpl()

Implements the IsMarshalByRef property and determines whether the Type is marshaled by reference.

(Inherited from Type)
IsPointerImpl()

When overridden in a derived class, implements the IsPointer property and determines whether the Type is a pointer.

IsPointerImpl()

When overridden in a derived class, implements the IsPointer property and determines whether the Type is a pointer.

(Inherited from Type)
IsPrimitiveImpl()

When overridden in a derived class, implements the IsPrimitive property and determines whether the Type is one of the primitive types.

IsPrimitiveImpl()

When overridden in a derived class, implements the IsPrimitive property and determines whether the Type is one of the primitive types.

(Inherited from Type)
IsSubclassOf(Type)

Not supported for incomplete generic type parameters.

IsValueTypeImpl()

Implements the IsValueType property and determines whether the Type is a value type; that is, not a class or an interface.

IsValueTypeImpl()

Implements the IsValueType property and determines whether the Type is a value type; that is, not a class or an interface.

(Inherited from Type)
MakeArrayType()

Returns the type of a one-dimensional array whose element type is the generic type parameter.

MakeArrayType(Int32)

Returns the type of an array whose element type is the generic type parameter, with the specified number of dimensions.

MakeByRefType()

Returns a Type object that represents the current generic type parameter when passed as a reference parameter.

MakeGenericType(Type[])

Not valid for incomplete generic type parameters.

MakePointerType()

Returns a Type object that represents a pointer to the current generic type parameter.

MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
SetBaseTypeConstraint(Type)

Sets the base type that a type must inherit in order to be substituted for the type parameter.

SetBaseTypeConstraintCore(Type)

When overridden in a derived class, sets the base type that a type must inherit in order to be substituted for the type parameter.

SetCustomAttribute(ConstructorInfo, Byte[])

Sets a custom attribute using a specified custom attribute blob.

SetCustomAttribute(CustomAttributeBuilder)

Set a custom attribute using a custom attribute builder.

SetCustomAttributeCore(ConstructorInfo, ReadOnlySpan<Byte>)

When overridden in a derived class, sets a custom attribute on this assembly.

SetGenericParameterAttributes(GenericParameterAttributes)

Sets the variance characteristics and special constraints of the generic parameter, such as the parameterless constructor constraint.

SetGenericParameterAttributesCore(GenericParameterAttributes)

When overridden in a derived class, sets the variance characteristics and special constraints of the generic parameter, such as the parameterless constructor constraint.

SetInterfaceConstraints(Type[])

Sets the interfaces a type must implement in order to be substituted for the type parameter.

SetInterfaceConstraintsCore(Type[])

When overridden in a derived class, sets the interfaces a type must implement in order to be substituted for the type parameter.

ToString()

Returns a string representation of the current generic type parameter.

Explicit Interface Implementations

_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from MemberInfo)
_MemberInfo.GetType()

Gets a Type object representing the MemberInfo class.

(Inherited from MemberInfo)
_MemberInfo.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.

(Inherited from MemberInfo)
_MemberInfo.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from MemberInfo)
_MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.

(Inherited from MemberInfo)
_Type.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Type)
_Type.GetTypeInfo(UInt32, UInt32, IntPtr)

Retrieves the type information for an object, which can then be used to get the type information for an interface.

(Inherited from Type)
_Type.GetTypeInfoCount(UInt32)

Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Type)
_Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Provides access to properties and methods exposed by an object.

(Inherited from Type)
ICustomAttributeProvider.GetCustomAttributes(Boolean)

Returns an array of all of the custom attributes defined on this member, excluding named attributes, or an empty array if there are no custom attributes.

(Inherited from MemberInfo)
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean)

Returns an array of custom attributes defined on this member, identified by type, or an empty array if there are no custom attributes of that type.

(Inherited from MemberInfo)
ICustomAttributeProvider.IsDefined(Type, Boolean)

Indicates whether one or more instance of attributeType is defined on this member.

(Inherited from MemberInfo)
IReflectableType.GetTypeInfo()

Returns a representation of the current type as a TypeInfo object.

(Inherited from TypeInfo)

Extension Methods

GetCustomAttribute(MemberInfo, Type, Boolean)

Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttribute(MemberInfo, Type)

Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttribute<T>(MemberInfo, Boolean)

Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttribute<T>(MemberInfo)

Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttributes(MemberInfo, Boolean)

Retrieves a collection of custom attributes that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo, Type, Boolean)

Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo, Type)

Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

GetCustomAttributes(MemberInfo)

Retrieves a collection of custom attributes that are applied to a specified member.

GetCustomAttributes<T>(MemberInfo, Boolean)

Retrieves a collection of custom attributes of a specified type that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes<T>(MemberInfo)

Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

IsDefined(MemberInfo, Type, Boolean)

Indicates whether custom attributes of a specified type are applied to a specified member, and, optionally, applied to its ancestors.

IsDefined(MemberInfo, Type)

Indicates whether custom attributes of a specified type are applied to a specified member.

GetTypeInfo(Type)

Returns the TypeInfo representation of the specified type.

GetMetadataToken(MemberInfo)

Gets a metadata token for the given member, if available.

HasMetadataToken(MemberInfo)

Returns a value that indicates whether a metadata token is available for the specified member.

GetRuntimeEvent(Type, String)

Retrieves an object that represents the specified event.

GetRuntimeEvents(Type)

Retrieves a collection that represents all the events defined on a specified type.

GetRuntimeField(Type, String)

Retrieves an object that represents a specified field.

GetRuntimeFields(Type)

Retrieves a collection that represents all the fields defined on a specified type.

GetRuntimeInterfaceMap(TypeInfo, Type)

Returns an interface mapping for the specified type and the specified interface.

GetRuntimeMethod(Type, String, Type[])

Retrieves an object that represents a specified method.

GetRuntimeMethods(Type)

Retrieves a collection that represents all methods defined on a specified type.

GetRuntimeProperties(Type)

Retrieves a collection that represents all the properties defined on a specified type.

GetRuntimeProperty(Type, String)

Retrieves an object that represents a specified property.

GetConstructor(Type, Type[])
GetConstructors(Type)
GetEvent(Type, String, BindingFlags)
GetEvents(Type, BindingFlags)
GetFields(Type)
GetGenericArguments(Type)
GetMembers(Type)
GetMethods(Type)
GetNestedType(Type, String, BindingFlags)
GetProperties(Type)
GetProperty(Type, String, BindingFlags)
GetProperty(Type, String, Type, Type[])
IsAssignableFrom(Type, Type)
IsInstanceOfType(Type, Object)

Applies to

See also