GenericTypeParameterBuilder GenericTypeParameterBuilder GenericTypeParameterBuilder GenericTypeParameterBuilder Class

Definição

Define e cria parâmetros de tipo genérico para métodos e tipos genéricos definidos dinamicamente.Defines and creates generic type parameters for dynamically defined generic types and methods. Essa classe não pode ser herdada.This class cannot be inherited.

public ref class GenericTypeParameterBuilder sealed : System::Reflection::TypeInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder : System.Reflection.TypeInfo
type GenericTypeParameterBuilder = class
    inherit TypeInfo
Public NotInheritable Class GenericTypeParameterBuilder
Inherits TypeInfo
Herança
GenericTypeParameterBuilderGenericTypeParameterBuilderGenericTypeParameterBuilderGenericTypeParameterBuilder
Atributos

Exemplos

O exemplo de código a seguir cria um tipo genérico com dois parâmetros de tipo e salva-os no assembly GenericEmitExample1. dll.The following code example creates a generic type with two type parameters, and saves them in the assembly GenericEmitExample1.dll. Você pode usar o ILDASM. exe (desmontador de Il) para exibir os tipos gerados.You can use the Ildasm.exe (IL Disassembler) to view the generated types. Para obter uma explicação mais detalhada das etapas envolvidas na definição de um tipo genérico dinâmico, consulte Como: definir um tipo genérico com a emissão de reflexão.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

Comentários

Você pode obter uma matriz de GenericTypeParameterBuilder objetos usando o método TypeBuilder.DefineGenericParameters para adicionar parâmetros de tipo a um tipo dinâmico, tornando-o um tipo genérico ou usando o MethodBuilder.DefineGenericParameters método para adicionar parâmetros de tipo a um método dinâmico.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 os GenericTypeParameterBuilder objetos para adicionar restrições aos parâmetros de tipo.Use the GenericTypeParameterBuilder objects to add constraints to the type parameters. As restrições são de três tipos:Constraints are of three kinds:

  • A restrição de tipo base especifica que qualquer tipo atribuído ao parâmetro de tipo genérico deve derivar de um tipo base específico.The base type constraint specifies that any type assigned to the generic type parameter must derive from a particular base type. Defina essa restrição usando o SetBaseTypeConstraint método.Set this constraint by using the SetBaseTypeConstraint method.

  • Uma restrição de interface especifica que qualquer tipo atribuído ao parâmetro de tipo genérico deve implementar uma interface específica.An interface constraint specifies that any type assigned to the generic type parameter must implement a particular interface. Defina as restrições de interface usando o SetInterfaceConstraints método.Set the interface constraints by using the SetInterfaceConstraints method.

  • Restrições especiais especificam que qualquer tipo atribuído ao parâmetro de tipo genérico deve ter um construtor sem parâmetros, deve ser um tipo de referência ou deve ser um tipo de valor.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. Defina as restrições especiais para um parâmetro de tipo usando o SetGenericParameterAttributes método.Set the special constraints for a type parameter by using the SetGenericParameterAttributes method.

Restrições de interface e restrições especiais não podem ser recuperadas usando GenericTypeParameterBuilder métodos da classe.Interface constraints and special constraints cannot be retrieved using methods of the GenericTypeParameterBuilder class. Depois de criar o tipo genérico que contém os parâmetros de tipo, você pode usar seu Type objeto para refletir as restrições.Once you have created the generic type that contains the type parameters, you can use its Type object to reflect the constraints. Use o Type.GetGenericArguments método para obter os parâmetros de tipo e para cada parâmetro de tipo, Type.GetGenericParameterConstraints use o método para obter a restrição de tipo base e as restrições Type.GenericParameterAttributes de interface e a propriedade para obter as restrições especiais.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.

Propriedades

Assembly Assembly Assembly Assembly

Obtém um objeto Assembly que representa o assembly dinâmico que contém a definição de tipo genérico à qual o parâmetro de tipo atual pertence.Gets an Assembly object representing the dynamic assembly that contains the generic type definition the current type parameter belongs to.

AssemblyQualifiedName AssemblyQualifiedName AssemblyQualifiedName AssemblyQualifiedName

Obtém null em todos os casos.Gets null in all cases.

Attributes Attributes Attributes Attributes
BaseType BaseType BaseType BaseType

Obtém a restrição de tipo base do parâmetro de tipo genérico atual.Gets the base type constraint of the current generic type parameter.

ContainsGenericParameters ContainsGenericParameters ContainsGenericParameters ContainsGenericParameters

Obtém true em todos os casos.Gets true in all cases.

CustomAttributes CustomAttributes CustomAttributes CustomAttributes

Obtém uma coleção que contém os atributos personalizados desse membro.Gets a collection that contains this member's custom attributes.

(Inherited from MemberInfo)
DeclaringMethod DeclaringMethod DeclaringMethod DeclaringMethod

Obtém um MethodInfo que representa o método declarativo, se o GenericTypeParameterBuilder atual representa um parâmetro de tipo de um método genérico.Gets a MethodInfo that represents the declaring method, if the current GenericTypeParameterBuilder represents a type parameter of a generic method.

DeclaringType DeclaringType DeclaringType DeclaringType

Obtém a definição de tipo genérico ou definição de método genérico à qual o parâmetro de tipo genérico pertence.Gets the generic type definition or generic method definition to which the generic type parameter belongs.

FullName FullName FullName FullName

Obtém null em todos os casos.Gets null in all cases.

GenericParameterAttributes GenericParameterAttributes GenericParameterAttributes GenericParameterAttributes

Obtém uma combinação de GenericParameterAttributes sinalizadores que descrevem a covariância e restrições especiais do parâmetro de tipo genérico atual.Gets a combination of GenericParameterAttributes flags that describe the covariance and special constraints of the current generic type parameter.

GenericParameterPosition GenericParameterPosition GenericParameterPosition GenericParameterPosition

Obtém a posição do parâmetro de tipo na lista de parâmetros de tipo do método ou tipo genérico que declarou o parâmetro.Gets the position of the type parameter in the type parameter list of the generic type or method that declared the parameter.

GenericTypeArguments GenericTypeArguments GenericTypeArguments GenericTypeArguments
GUID GUID GUID GUID

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

HasElementType HasElementType HasElementType HasElementType

Obtém um valor que indica se o Type atual abrange ou se refere a outro tipo; ou seja, se o Type atual é uma matriz, um ponteiro ou é passado por referência.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)
IsAbstract IsAbstract IsAbstract IsAbstract

Obtém um valor que indica se o Type é abstrato e deve ser substituído.Gets a value indicating whether the Type is abstract and must be overridden.

(Inherited from Type)
IsAnsiClass IsAnsiClass IsAnsiClass IsAnsiClass

Obtém um valor que indica se o atributo de formato da cadeia de caracteres AnsiClass está selecionado para o Type.Gets a value indicating whether the string format attribute AnsiClass is selected for the Type.

(Inherited from Type)
IsArray IsArray IsArray IsArray

Obtém um valor que indica se o tipo é uma matriz.Gets a value that indicates whether the type is an array.

(Inherited from Type)
IsAutoClass IsAutoClass IsAutoClass IsAutoClass

Obtém um valor que indica se o atributo de formato da cadeia de caracteres AutoClass está selecionado para o Type.Gets a value indicating whether the string format attribute AutoClass is selected for the Type.

(Inherited from Type)
IsAutoLayout IsAutoLayout IsAutoLayout IsAutoLayout

Obtém um valor que indica se os campos do tipo atual são apresentados automaticamente pelo Common Language Runtime.Gets a value indicating whether the fields of the current type are laid out automatically by the common language runtime.

(Inherited from Type)
IsByRef IsByRef IsByRef IsByRef

Obtém um valor que indica se o Type é aprovado por referência.Gets a value indicating whether the Type is passed by reference.

(Inherited from Type)
IsByRefLike IsByRefLike IsByRefLike IsByRefLike
IsClass IsClass IsClass IsClass

Obtém um valor que indica se o Type é uma classe ou um delegado; ou seja, não um tipo de valor ou interface.Gets a value indicating whether the Type is a class or a delegate; that is, not a value type or interface.

(Inherited from Type)
IsCollectible IsCollectible IsCollectible IsCollectible

Obtém um valor que indica se este objeto MemberInfo faz parte de um assembly mantido em uma coleção AssemblyLoadContext.Gets a value that indicates whether this MemberInfo object is part of an assembly held in a collectible AssemblyLoadContext.

(Inherited from MemberInfo)
IsCOMObject IsCOMObject IsCOMObject IsCOMObject

Obtém um valor que indica se o Type é um objeto COM.Gets a value indicating whether the Type is a COM object.

(Inherited from Type)
IsConstructedGenericType IsConstructedGenericType IsConstructedGenericType IsConstructedGenericType

Obtém um valor que indica se este objeto representa um tipo genérico construído.Gets a value that indicates whether this object represents a constructed generic type.

IsContextful IsContextful IsContextful IsContextful

Obtém um valor que indica se o Type pode ser hospedado em um contexto.Gets a value indicating whether the Type can be hosted in a context.

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

Obtém um valor que indica se os campos do tipo atual são apresentados em deslocamentos explicitamente especificados.Gets a value indicating whether the fields of the current type are laid out at explicitly specified offsets.

(Inherited from Type)
IsGenericMethodParameter IsGenericMethodParameter IsGenericMethodParameter IsGenericMethodParameter Inherited from Type
IsGenericParameter IsGenericParameter IsGenericParameter IsGenericParameter

Obtém true em todos os casos.Gets true in all cases.

IsGenericType IsGenericType IsGenericType IsGenericType

Retorna false em todos os casos.Returns false in all cases.

IsGenericTypeDefinition IsGenericTypeDefinition IsGenericTypeDefinition IsGenericTypeDefinition

Obtém false em todos os casos.Gets false in all cases.

IsGenericTypeParameter IsGenericTypeParameter IsGenericTypeParameter IsGenericTypeParameter Inherited from Type
IsImport IsImport IsImport IsImport

Obtém um valor que indica se o Type tem um atributo ComImportAttribute aplicado, indicando que ele foi importado de uma biblioteca de tipos COM.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)
IsInterface IsInterface IsInterface IsInterface

Obtém um valor que indica se o Type é uma interface, ou seja, não é uma classe ou um tipo de valor.Gets a value indicating whether the Type is an interface; that is, not a class or a value type.

(Inherited from Type)
IsLayoutSequential IsLayoutSequential IsLayoutSequential IsLayoutSequential

Obtém um valor que indica se os campos do tipo atual são apresentados em sequência, na ordem em que foram definidos ou emitidos para os metadados.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)
IsMarshalByRef IsMarshalByRef IsMarshalByRef IsMarshalByRef

Obtém um valor que indica se é realizado marshal no Type por referência.Gets a value indicating whether the Type is marshaled by reference.

(Inherited from Type)
IsNested IsNested IsNested IsNested

Obtém um valor que indica se o objeto atual Type representa um tipo cuja definição está aninhada dentro da definição de outro tipo.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)
IsNestedAssembly IsNestedAssembly IsNestedAssembly IsNestedAssembly

Obtém um valor que indica se o Type é aninhado e visível somente dentro de seu próprio assembly.Gets a value indicating whether the Type is nested and visible only within its own assembly.

(Inherited from Type)
IsNestedFamANDAssem IsNestedFamANDAssem IsNestedFamANDAssem IsNestedFamANDAssem

Obtém um valor que indica se o Type é aninhado e visíveis somente para classes que pertencem à sua própria família e ao seu próprio assembly.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)
IsNestedFamily IsNestedFamily IsNestedFamily IsNestedFamily

Obtém um valor que indica se o Type é aninhado e visível somente dentro de sua própria família.Gets a value indicating whether the Type is nested and visible only within its own family.

(Inherited from Type)
IsNestedFamORAssem IsNestedFamORAssem IsNestedFamORAssem IsNestedFamORAssem

Obtém um valor que indica se o Type é aninhado e visíveis somente para classes que pertençam à sua própria família ou ao seu próprio assembly.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)
IsNestedPrivate IsNestedPrivate IsNestedPrivate IsNestedPrivate

Obtém um valor que indica se o Type é aninhado e declarado privado.Gets a value indicating whether the Type is nested and declared private.

(Inherited from Type)
IsNestedPublic IsNestedPublic IsNestedPublic IsNestedPublic

Obtém um valor que indica se uma classe é aninhada e declarada pública.Gets a value indicating whether a class is nested and declared public.

(Inherited from Type)
IsNotPublic IsNotPublic IsNotPublic IsNotPublic

Obtém um valor que indica se o Type não está declarado como público.Gets a value indicating whether the Type is not declared public.

(Inherited from Type)
IsPointer IsPointer IsPointer IsPointer

Obtém um valor que indica se o Type é um ponteiro.Gets a value indicating whether the Type is a pointer.

(Inherited from Type)
IsPrimitive IsPrimitive IsPrimitive IsPrimitive

Obtém um valor que indica se o Type é um dos tipos primitivos.Gets a value indicating whether the Type is one of the primitive types.

(Inherited from Type)
IsPublic IsPublic IsPublic IsPublic

Obtém um valor que indica se o Type está declarado como público.Gets a value indicating whether the Type is declared public.

(Inherited from Type)
IsSealed IsSealed IsSealed IsSealed

Obtém um valor que indica se o Type está declarado selado.Gets a value indicating whether the Type is declared sealed.

(Inherited from Type)
IsSecurityCritical IsSecurityCritical IsSecurityCritical IsSecurityCritical

Obtém um valor que indica se o tipo atual é crítico para segurança ou crítico para segurança e disponível no código transparente no nível de confiança atual e, portanto, pode realizar operações críticas.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 IsSecuritySafeCritical IsSecuritySafeCritical IsSecuritySafeCritical

Obtém um valor que indica se o tipo é crítico para segurança e disponível no código transparente no nível de confiança atual, ou seja, se ele pode realizar operações críticas e ser acessado por código transparente.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 IsSecurityTransparent IsSecurityTransparent IsSecurityTransparent

Obtém um valor que indica que se o tipo atual é transparente no nível de confiança atual e, portanto, não pode realizar operações críticas.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 IsSerializable IsSerializable
IsSignatureType IsSignatureType IsSignatureType IsSignatureType Inherited from Type
IsSpecialName IsSpecialName IsSpecialName IsSpecialName

Obtém um valor que indica se o tipo tem um nome que exige tratamento especial.Gets a value indicating whether the type has a name that requires special handling.

(Inherited from Type)
IsSZArray IsSZArray IsSZArray IsSZArray
IsTypeDefinition IsTypeDefinition IsTypeDefinition IsTypeDefinition
IsUnicodeClass IsUnicodeClass IsUnicodeClass IsUnicodeClass

Obtém um valor que indica se o atributo de formato da cadeia de caracteres UnicodeClass está selecionado para o Type.Gets a value indicating whether the string format attribute UnicodeClass is selected for the Type.

(Inherited from Type)
IsValueType IsValueType IsValueType IsValueType

Obtém um valor que indica se o Type é um tipo de valor.Gets a value indicating whether the Type is a value type.

(Inherited from Type)
IsVariableBoundArray IsVariableBoundArray IsVariableBoundArray IsVariableBoundArray
IsVisible IsVisible IsVisible IsVisible

Obtém um valor que indica se Type pode ser acessado pelo código fora do assembly.Gets a value indicating whether the Type can be accessed by code outside the assembly.

(Inherited from Type)
MemberType MemberType MemberType MemberType

Obtém um valor MemberTypes que indica que esse membro é um tipo ou um tipo aninhado.Gets a MemberTypes value indicating that this member is a type or a nested type.

(Inherited from Type)
MetadataToken MetadataToken MetadataToken MetadataToken

Obtém um valor que identifica um elemento de metadados.Gets a value that identifies a metadata element.

(Inherited from MemberInfo)
Module Module Module Module

Obtém o módulo dinâmico que contém o parâmetro de tipo genérico.Gets the dynamic module that contains the generic type parameter.

Name Name Name Name

Obtém o nome do parâmetro de tipo genérico.Gets the name of the generic type parameter.

Namespace Namespace Namespace Namespace

Obtém null em todos os casos.Gets null in all cases.

ReflectedType ReflectedType ReflectedType ReflectedType

Obtém o objeto Type que foi usado para obter o GenericTypeParameterBuilder.Gets the Type object that was used to obtain the GenericTypeParameterBuilder.

StructLayoutAttribute StructLayoutAttribute StructLayoutAttribute StructLayoutAttribute

Obtém um StructLayoutAttribute que descreve o layout do tipo atual.Gets a StructLayoutAttribute that describes the layout of the current type.

(Inherited from Type)
TypeHandle TypeHandle TypeHandle TypeHandle

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

TypeInitializer TypeInitializer TypeInitializer TypeInitializer

Obtém o inicializador para o tipo.Gets the initializer for the type.

(Inherited from Type)
UnderlyingSystemType UnderlyingSystemType UnderlyingSystemType UnderlyingSystemType

Obtém o parâmetro de tipo genérico atual.Gets the current generic type parameter.

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Testa se o objeto fornecido é uma instância de EventToken e é igual à instância atual.Tests whether the given object is an instance of EventToken and is equal to the current instance.

Equals(Type) Equals(Type) Equals(Type) Equals(Type)

Determina se o tipo de sistema subjacente do Type atual é o mesmo que o tipo de sistema subjacente do Type especificado.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) FindInterfaces(TypeFilter, Object) FindInterfaces(TypeFilter, Object) FindInterfaces(TypeFilter, Object)

Retorna uma matriz de objetos Type que representa uma lista filtrada das interfaces implementadas ou herdadas pelo Type atual.Returns an array of Type objects representing a filtered list of interfaces implemented or inherited by the current Type.

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

Retorna uma matriz filtrada de objetos MemberInfo do tipo do membro especificado.Returns a filtered array of MemberInfo objects of the specified member type.

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

Quando substituído em uma classe derivada, implementa a propriedade Attributes e obtém uma combinação bit a bit dos valores de enumeração que indicam os atributos associados ao Type.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[]) GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[])

Pesquisa por um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.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[]) GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[])

Pesquisa o construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas.Searches for a constructor whose parameters match the specified argument types and modifiers, using the specified binding constraints.

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

Pesquisa um construtor de instância pública cujos parâmetros correspondem aos tipos na matriz especificada.Searches for a public instance constructor whose parameters match the types in the specified array.

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

Quando substituído em uma classe derivada, pesquisa por um construtor cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.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() GetConstructors() GetConstructors() GetConstructors()

Retorna todos os construtores públicos definidos para o Type atual.Returns all the public constructors defined for the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean) GetCustomAttributes(Boolean)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean) GetCustomAttributes(Type, Boolean)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData() GetCustomAttributesData()

Retorna uma lista de objetos CustomAttributeData que representam dados sobre os atributos que foram aplicados ao membro de destino.Returns a list of CustomAttributeData objects representing data about the attributes that have been applied to the target member.

(Inherited from MemberInfo)
GetDefaultMembers() GetDefaultMembers() GetDefaultMembers() GetDefaultMembers()

Procura os membros definidos para o Type atual, cujo DefaultMemberAttribute está definido.Searches for the members defined for the current Type whose DefaultMemberAttribute is set.

(Inherited from Type)
GetElementType() GetElementType() GetElementType() GetElementType()

Gera um NotSupportedException em todos os casos.Throws a NotSupportedException in all cases.

GetEnumName(Object) GetEnumName(Object) GetEnumName(Object) GetEnumName(Object)

Retorna o nome da constante que tem o valor especificado para o tipo de enumeração atual.Returns the name of the constant that has the specified value, for the current enumeration type.

(Inherited from Type)
GetEnumNames() GetEnumNames() GetEnumNames() GetEnumNames()

Retorna os nomes dos membros do tipo de enumeração atual.Returns the names of the members of the current enumeration type.

(Inherited from Type)
GetEnumUnderlyingType() GetEnumUnderlyingType() GetEnumUnderlyingType() GetEnumUnderlyingType()

Retorna o tipo subjacente do tipo de enumeração atual.Returns the underlying type of the current enumeration type.

(Inherited from Type)
GetEnumValues() GetEnumValues() GetEnumValues() GetEnumValues()

Retorna uma matriz de valores das constantes no tipo de enumeração especificado.Returns an array of the values of the constants in the current enumeration type.

(Inherited from Type)
GetEvent(String) GetEvent(String) GetEvent(String) GetEvent(String)

Retorna o objeto EventInfo que representa o evento público especificado.Returns the EventInfo object representing the specified public event.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetEvents() GetEvents() GetEvents() GetEvents()

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetEvents(BindingFlags) GetEvents(BindingFlags) GetEvents(BindingFlags) GetEvents(BindingFlags)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetField(String) GetField(String) GetField(String) GetField(String)

Pesquisa o campo público com o nome especificado.Searches for the public field with the specified name.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetFields() GetFields() GetFields() GetFields()

Retorna todos os campos públicos do Type atual.Returns all the public fields of the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetGenericArguments() GetGenericArguments() GetGenericArguments() GetGenericArguments()

Não é válido para parâmetros de tipo genérico.Not valid for generic type parameters.

GetGenericParameterConstraints() GetGenericParameterConstraints() GetGenericParameterConstraints() GetGenericParameterConstraints()
GetGenericTypeDefinition() GetGenericTypeDefinition() GetGenericTypeDefinition() GetGenericTypeDefinition()

Não é válido para parâmetros de tipo genérico.Not valid for generic type parameters.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Retorna um código hash de inteiro de 32 bits para a instância atual.Returns a 32-bit integer hash code for the current instance.

GetInterface(String) GetInterface(String) GetInterface(String) GetInterface(String)

Pesquisa a interface com o nome especificado.Searches for the interface with the specified name.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetInterfaceMap(Type) GetInterfaceMap(Type) GetInterfaceMap(Type) GetInterfaceMap(Type)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetInterfaces() GetInterfaces() GetInterfaces() GetInterfaces()

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetMember(String) GetMember(String) GetMember(String) GetMember(String)

Pesquisa a propriedade pública com o nome especificado.Searches for the public members with the specified name.

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

Pesquisa os membros especificados usando as restrições de associação especificadas.Searches for the specified members, using the specified binding constraints.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetMembers() GetMembers() GetMembers() GetMembers()

Retorna todos os membros públicos do Type atual.Returns all the public members of the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetMethod(String) GetMethod(String) GetMethod(String) GetMethod(String)

Pesquisa o método público com o nome especificado.Searches for the public method with the specified name.

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

Pesquisa o método especificado, usando as restrições de associação especificadas.Searches for the specified method, using the specified binding constraints.

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

Pesquisa o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.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[]) GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[]) GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[]) GetMethod(String, BindingFlags, Binder, Type[], ParameterModifier[])

Pesquisa o método especificado cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas.Searches for the specified method whose parameters match the specified argument types and modifiers, using the specified binding constraints.

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

Pesquisa o método público especificado cujos parâmetros correspondem aos tipos de argumento especificados.Searches for the specified public method whose parameters match the specified argument types.

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

Pesquisa o método público especificado cujos parâmetros correspondem aos modificadores e tipos de argumento especificados.Searches for the specified public method whose parameters match the specified argument types and modifiers.

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

Quando substituído em uma classe derivada, pesquisa o método especificado, cujos parâmetros correspondem aos tipos de argumento e modificadores especificados, usando as restrições de associação especificadas e a convenção de chamada especificada.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[]) GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) GetMethodImpl(String, Int32, BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) Inherited from Type
GetMethods() GetMethods() GetMethods() GetMethods()

Retorna todos os métodos públicos do Type atual.Returns all the public methods of the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetNestedType(String) GetNestedType(String) GetNestedType(String) GetNestedType(String)

Pesquisa o tipo aninhado público com o nome especificado.Searches for the public nested type with the specified name.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetNestedTypes() GetNestedTypes() GetNestedTypes() GetNestedTypes()

Retorna os tipos públicos aninhados no Type atual.Returns the public types nested in the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetProperties() GetProperties() GetProperties() GetProperties()

Retorna todas as propriedades públicas do Type atual.Returns all the public properties of the current Type.

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

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

GetProperty(String) GetProperty(String) GetProperty(String) GetProperty(String)

Pesquisa a propriedade pública com o nome especificado.Searches for the public property with the specified name.

(Inherited from Type)
GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags) GetProperty(String, BindingFlags)

Pesquisa a propriedade especificada usando as restrições de associação especificadas.Searches for the specified property, using the specified binding constraints.

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

Pesquisa a propriedade especificada cujos parâmetros correspondem aos modificadores e tipos de argumento especificados, usando as restrições de associação especificadas.Searches for the specified property whose parameters match the specified argument types and modifiers, using the specified binding constraints.

(Inherited from Type)
GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type) GetProperty(String, Type)

Pesquisa a propriedade pública com o nome e tipo retornado especificados.Searches for the public property with the specified name and return type.

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

Pesquisa a propriedade pública especificada cujos parâmetros correspondem aos tipos de argumento especificados.Searches for the specified public property whose parameters match the specified argument types.

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

Pesquisa a propriedade pública especificada cujos parâmetros correspondem aos tipos de argumento e modificadores especificados.Searches for the specified public property whose parameters match the specified argument types and modifiers.

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

Pesquisa a propriedade pública especificada cujos parâmetros correspondem aos tipos de argumento especificados.Searches for the specified public property whose parameters match the specified argument types.

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

Quando substituído em uma classe derivada, pesquisa a propriedade especificada cujos parâmetros correspondem aos modificadores e tipos de argumento especificados, usando as restrições de associação especificadas.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)
GetType() GetType() GetType() GetType()

Obtém o Type atual.Gets the current Type.

(Inherited from Type)
GetTypeCodeImpl() GetTypeCodeImpl() GetTypeCodeImpl() GetTypeCodeImpl()

Retorna o código de tipo subjacente desta instância Type.Returns the underlying type code of this Type instance.

(Inherited from Type)
HasElementTypeImpl() HasElementTypeImpl() HasElementTypeImpl() HasElementTypeImpl()

Quando substituído em uma classe derivada, implementa a propriedade HasElementType e determina se o Type atual abrange ou se refere a outro tipo, ou seja, se o Type atual é uma matriz, um ponteiro ou é passado por referência.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) HasSameMetadataDefinitionAs(MemberInfo) HasSameMetadataDefinitionAs(MemberInfo) HasSameMetadataDefinitionAs(MemberInfo) Inherited from MemberInfo
InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[]) InvokeMember(String, BindingFlags, Binder, Object, Object[])

Invoca o membro especificado, usando as restrições de associação especificadas e fazendo a correspondência da lista de argumentos especificada.Invokes the specified member, using the specified binding constraints and matching the specified argument list.

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

Invoca o membro especificado, usando as restrições de associação especificadas e fazendo a correspondência da lista de argumentos e cultura especificadas.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[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[]) InvokeMember(String, BindingFlags, Binder, Object, Object[], ParameterModifier[], CultureInfo, String[])

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

IsArrayImpl() IsArrayImpl() IsArrayImpl() IsArrayImpl()

Quando substituído em uma classe derivada, implementa a propriedade IsArray e determina se o Type é uma matriz.When overridden in a derived class, implements the IsArray property and determines whether the Type is an array.

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

Gera uma exceção NotSupportedException em todos os casos.Throws a NotSupportedException exception in all cases.

IsAssignableFrom(TypeInfo) IsAssignableFrom(TypeInfo) IsAssignableFrom(TypeInfo) IsAssignableFrom(TypeInfo)

Gera uma exceção NotSupportedException em todos os casos.Throws a NotSupportedException exception in all cases.

IsByRefImpl() IsByRefImpl() IsByRefImpl() IsByRefImpl()

Quando substituído em uma classe derivada, implementa a propriedade IsByRef e determina se o Type é passado por referência.When overridden in a derived class, implements the IsByRef property and determines whether the Type is passed by reference.

(Inherited from Type)
IsCOMObjectImpl() IsCOMObjectImpl() IsCOMObjectImpl() IsCOMObjectImpl()

Quando substituído em uma classe derivada, implementa a propriedade IsCOMObject e determina se o Type é um objeto COM.When overridden in a derived class, implements the IsCOMObject property and determines whether the Type is a COM object.

(Inherited from Type)
IsContextfulImpl() IsContextfulImpl() IsContextfulImpl() IsContextfulImpl()

Implementa a propriedade IsContextful e determina se o Type pode ser hospedado em um contexto.Implements the IsContextful property and determines whether the Type can be hosted in a context.

(Inherited from Type)
IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean) IsDefined(Type, Boolean)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

IsEnumDefined(Object) IsEnumDefined(Object) IsEnumDefined(Object) IsEnumDefined(Object)

Retorna um valor que indica se o valor especificado existe no tipo de enumeração atual.Returns a value that indicates whether the specified value exists in the current enumeration type.

(Inherited from Type)
IsEquivalentTo(Type) IsEquivalentTo(Type) IsEquivalentTo(Type) IsEquivalentTo(Type)

Determina se dois tipos COM têm a mesma identidade e são elegíveis para equivalência de tipo.Determines whether two COM types have the same identity and are eligible for type equivalence.

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

Implementa a propriedade IsMarshalByRef e determina se é realizado marshal no Type por referência.Implements the IsMarshalByRef property and determines whether the Type is marshaled by reference.

(Inherited from Type)
IsPointerImpl() IsPointerImpl() IsPointerImpl() IsPointerImpl()

Quando substituído em uma classe derivada, implementa a propriedade IsPointer e determina se o Type é um ponteiro.When overridden in a derived class, implements the IsPointer property and determines whether the Type is a pointer.

(Inherited from Type)
IsPrimitiveImpl() IsPrimitiveImpl() IsPrimitiveImpl() IsPrimitiveImpl()

Quando substituído em uma classe derivada, implementa a propriedade IsPrimitive e determina se o Type é um dos tipos primitivos.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) IsSubclassOf(Type) IsSubclassOf(Type) IsSubclassOf(Type)

Sem suporte para parâmetros de tipo genérico incompletos.Not supported for incomplete generic type parameters.

IsValueTypeImpl() IsValueTypeImpl() IsValueTypeImpl() IsValueTypeImpl()

Implementa a propriedade IsValueType e determina se o Type é um tipo de valor, ou seja, não é uma classe nem uma interface.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() MakeArrayType() MakeArrayType() MakeArrayType()

Retorna o tipo de uma matriz unidimensional cujo tipo de elemento é o parâmetro de tipo genérico.Returns the type of a one-dimensional array whose element type is the generic type parameter.

MakeArrayType(Int32) MakeArrayType(Int32) MakeArrayType(Int32) MakeArrayType(Int32)

Retorna o tipo de uma matriz cujo tipo de elemento é o parâmetro de tipo genérico, com o número de dimensões especificado.Returns the type of an array whose element type is the generic type parameter, with the specified number of dimensions.

MakeByRefType() MakeByRefType() MakeByRefType() MakeByRefType()

Retorna um objeto Type que representa o parâmetro de tipo genérico atual quando passado como um parâmetro de referência.Returns a Type object that represents the current generic type parameter when passed as a reference parameter.

MakeGenericType(Type[]) MakeGenericType(Type[]) MakeGenericType(Type[]) MakeGenericType(Type[])

Não é válido para parâmetros de tipo genérico incompletos.Not valid for incomplete generic type parameters.

MakePointerType() MakePointerType() MakePointerType() MakePointerType()

Retorna um objeto Type que representa um ponteiro para o parâmetro de tipo genérico atual.Returns a Type object that represents a pointer to the current generic type parameter.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
SetBaseTypeConstraint(Type) SetBaseTypeConstraint(Type) SetBaseTypeConstraint(Type) SetBaseTypeConstraint(Type)

Define o tipo base que um tipo deve herdar para ser substituído pelo parâmetro de tipo.Sets the base type that a type must inherit in order to be substituted for the type parameter.

SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[]) SetCustomAttribute(ConstructorInfo, Byte[])

Define um atributo personalizado usando um blob de atributo personalizado especificado.Sets a custom attribute using a specified custom attribute blob.

SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder) SetCustomAttribute(CustomAttributeBuilder)

Defina um atributo personalizado usando um construtor de atributos personalizados.Set a custom attribute using a custom attribute builder.

SetGenericParameterAttributes(GenericParameterAttributes) SetGenericParameterAttributes(GenericParameterAttributes) SetGenericParameterAttributes(GenericParameterAttributes) SetGenericParameterAttributes(GenericParameterAttributes)

Define as características de variação e restrições especiais do parâmetro genérico, tais como a restrição de construtor sem parâmetros.Sets the variance characteristics and special constraints of the generic parameter, such as the parameterless constructor constraint.

SetInterfaceConstraints(Type[]) SetInterfaceConstraints(Type[]) SetInterfaceConstraints(Type[]) SetInterfaceConstraints(Type[])

Define as interfaces que um tipo deve implementar para ser substituído pelo parâmetro de tipo.Sets the interfaces a type must implement in order to be substituted for the type parameter.

ToString() ToString() ToString() ToString()

Retorna uma representação de cadeia de caracteres do parâmetro de tipo genérico atual.Returns a string representation of the current generic type parameter.

Implantações explícitas de interface

ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) ICustomAttributeProvider.GetCustomAttributes(Boolean) Inherited from MemberInfo
ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) ICustomAttributeProvider.GetCustomAttributes(Type, Boolean) Inherited from MemberInfo
ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) ICustomAttributeProvider.IsDefined(Type, Boolean) Inherited from MemberInfo
_MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr) _MemberInfo.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from MemberInfo)
_MemberInfo.GetType() _MemberInfo.GetType() _MemberInfo.GetType() _MemberInfo.GetType()

Obtém um objeto Type que representa a classe MemberInfo.Gets a Type object representing the MemberInfo class.

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

Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.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) _MemberInfo.GetTypeInfoCount(UInt32) _MemberInfo.GetTypeInfoCount(UInt32) _MemberInfo.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).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) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _MemberInfo.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object.

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

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.Maps a set of names to a corresponding set of dispatch identifiers.

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

Recupera as informações do tipo de um objeto, que podem ser usadas para obter informações de tipo para uma interface.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) _Type.GetTypeInfoCount(UInt32) _Type.GetTypeInfoCount(UInt32) _Type.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).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) _Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Type.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.Provides access to properties and methods exposed by an object.

(Inherited from Type)

Métodos de Extensão

GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type) GetCustomAttribute(MemberInfo, Type)

Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado.Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean) GetCustomAttribute(MemberInfo, Type, Boolean)

Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.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) GetCustomAttribute<T>(MemberInfo) GetCustomAttribute<T>(MemberInfo) GetCustomAttribute<T>(MemberInfo)

Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado.Retrieves a custom attribute of a specified type that is applied to a specified member.

GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean) GetCustomAttribute<T>(MemberInfo, Boolean)

Recupera um atributo personalizado de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a custom attribute of a specified type that is applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo) GetCustomAttributes(MemberInfo)

Recupera uma coleção de atributos personalizados que são aplicados a um membro especificado.Retrieves a collection of custom attributes that are applied to a specified member.

GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean) GetCustomAttributes(MemberInfo, Boolean)

Recupera uma coleção de atributos personalizados aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.Retrieves a collection of custom attributes that are applied to a specified member, and optionally inspects the ancestors of that member.

GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type) GetCustomAttributes(MemberInfo, Type)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean) GetCustomAttributes(MemberInfo, Type, Boolean)

Recupera uma coleção de atributos personalizados de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.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) GetCustomAttributes<T>(MemberInfo) GetCustomAttributes<T>(MemberInfo) GetCustomAttributes<T>(MemberInfo)

Recupera uma coleção de atributos personalizados de um tipo especificado que são aplicados a um membro especificado.Retrieves a collection of custom attributes of a specified type that are applied to a specified member.

GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean) GetCustomAttributes<T>(MemberInfo, Boolean)

Recupera uma coleção de atributos personalizados de um tipo especificado aplicado a um membro especificado e opcionalmente inspeciona os ancestrais desse membro.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.

IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type) IsDefined(MemberInfo, Type)

Indica se os atributos personalizados de um tipo especificados são aplicados a um membro especificado.Indicates whether custom attributes of a specified type are applied to a specified member.

IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean) IsDefined(MemberInfo, Type, Boolean)

Indica se os atributos personalizados de um tipo especificado são aplicados a um membro especificado e, opcionalmente, aplicados a seus ancestrais.Indicates whether custom attributes of a specified type are applied to a specified member, and, optionally, applied to its ancestors.

GetTypeInfo(Type) GetTypeInfo(Type) GetTypeInfo(Type) GetTypeInfo(Type)

Retorna a representação de TypeInfo do tipo especificado.Returns the TypeInfo representation of the specified type.

GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo) GetMetadataToken(MemberInfo)

Obtém um token de metadados para o membro fornecido, se disponível.Gets a metadata token for the given member, if available.

HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo) HasMetadataToken(MemberInfo)

Retorna um valor que indica se um token de metadados está disponível para o membro especificado.Returns a value that indicates whether a metadata token is available for the specified member.

GetRuntimeEvent(Type, String) GetRuntimeEvent(Type, String) GetRuntimeEvent(Type, String) GetRuntimeEvent(Type, String)

Recupera um objeto que representa o evento especificado.Retrieves an object that represents the specified event.

GetRuntimeEvents(Type) GetRuntimeEvents(Type) GetRuntimeEvents(Type) GetRuntimeEvents(Type)

Recupera uma coleção que representa todos os eventos definidos em um tipo especificado.Retrieves a collection that represents all the events defined on a specified type.

GetRuntimeField(Type, String) GetRuntimeField(Type, String) GetRuntimeField(Type, String) GetRuntimeField(Type, String)

Recupera um objeto que representa um campo especificado.Retrieves an object that represents a specified field.

GetRuntimeFields(Type) GetRuntimeFields(Type) GetRuntimeFields(Type) GetRuntimeFields(Type)

Recupera uma coleção que representa todos os campos definidos em um tipo especificado.Retrieves a collection that represents all the fields defined on a specified type.

GetRuntimeMethod(Type, String, Type[]) GetRuntimeMethod(Type, String, Type[]) GetRuntimeMethod(Type, String, Type[]) GetRuntimeMethod(Type, String, Type[])

Recupera um objeto que representa um método especificado.Retrieves an object that represents a specified method.

GetRuntimeMethods(Type) GetRuntimeMethods(Type) GetRuntimeMethods(Type) GetRuntimeMethods(Type)

Recupera uma coleção que representa todos os métodos definidos em um tipo especificado.Retrieves a collection that represents all methods defined on a specified type.

GetRuntimeProperties(Type) GetRuntimeProperties(Type) GetRuntimeProperties(Type) GetRuntimeProperties(Type)

Recupera uma coleção que representa todas as propriedades definidas em um tipo especificado.Retrieves a collection that represents all the properties defined on a specified type.

GetRuntimeProperty(Type, String) GetRuntimeProperty(Type, String) GetRuntimeProperty(Type, String) GetRuntimeProperty(Type, String)

Recupera um objeto que representa uma propriedade especificada.Retrieves an object that represents a specified property.

GetConstructor(Type, Type[]) GetConstructor(Type, Type[]) GetConstructor(Type, Type[]) GetConstructor(Type, Type[])
GetConstructors(Type) GetConstructors(Type) GetConstructors(Type) GetConstructors(Type)
GetConstructors(Type, BindingFlags) GetConstructors(Type, BindingFlags) GetConstructors(Type, BindingFlags) GetConstructors(Type, BindingFlags)
GetDefaultMembers(Type) GetDefaultMembers(Type) GetDefaultMembers(Type) GetDefaultMembers(Type)
GetEvent(Type, String) GetEvent(Type, String) GetEvent(Type, String) GetEvent(Type, String)
GetEvent(Type, String, BindingFlags) GetEvent(Type, String, BindingFlags) GetEvent(Type, String, BindingFlags) GetEvent(Type, String, BindingFlags)
GetEvents(Type) GetEvents(Type) GetEvents(Type) GetEvents(Type)
GetEvents(Type, BindingFlags) GetEvents(Type, BindingFlags) GetEvents(Type, BindingFlags) GetEvents(Type, BindingFlags)
GetField(Type, String) GetField(Type, String) GetField(Type, String) GetField(Type, String)
GetField(Type, String, BindingFlags) GetField(Type, String, BindingFlags) GetField(Type, String, BindingFlags) GetField(Type, String, BindingFlags)
GetFields(Type) GetFields(Type) GetFields(Type) GetFields(Type)
GetFields(Type, BindingFlags) GetFields(Type, BindingFlags) GetFields(Type, BindingFlags) GetFields(Type, BindingFlags)
GetGenericArguments(Type) GetGenericArguments(Type) GetGenericArguments(Type) GetGenericArguments(Type)
GetInterfaces(Type) GetInterfaces(Type) GetInterfaces(Type) GetInterfaces(Type)
GetMember(Type, String) GetMember(Type, String) GetMember(Type, String) GetMember(Type, String)
GetMember(Type, String, BindingFlags) GetMember(Type, String, BindingFlags) GetMember(Type, String, BindingFlags) GetMember(Type, String, BindingFlags)
GetMembers(Type) GetMembers(Type) GetMembers(Type) GetMembers(Type)
GetMembers(Type, BindingFlags) GetMembers(Type, BindingFlags) GetMembers(Type, BindingFlags) GetMembers(Type, BindingFlags)
GetMethod(Type, String) GetMethod(Type, String) GetMethod(Type, String) GetMethod(Type, String)
GetMethod(Type, String, BindingFlags) GetMethod(Type, String, BindingFlags) GetMethod(Type, String, BindingFlags) GetMethod(Type, String, BindingFlags)
GetMethod(Type, String, Type[]) GetMethod(Type, String, Type[]) GetMethod(Type, String, Type[]) GetMethod(Type, String, Type[])
GetMethods(Type) GetMethods(Type) GetMethods(Type) GetMethods(Type)
GetMethods(Type, BindingFlags) GetMethods(Type, BindingFlags) GetMethods(Type, BindingFlags) GetMethods(Type, BindingFlags)
GetNestedType(Type, String, BindingFlags) GetNestedType(Type, String, BindingFlags) GetNestedType(Type, String, BindingFlags) GetNestedType(Type, String, BindingFlags)
GetNestedTypes(Type, BindingFlags) GetNestedTypes(Type, BindingFlags) GetNestedTypes(Type, BindingFlags) GetNestedTypes(Type, BindingFlags)
GetProperties(Type) GetProperties(Type) GetProperties(Type) GetProperties(Type)
GetProperties(Type, BindingFlags) GetProperties(Type, BindingFlags) GetProperties(Type, BindingFlags) GetProperties(Type, BindingFlags)
GetProperty(Type, String) GetProperty(Type, String) GetProperty(Type, String) GetProperty(Type, String)
GetProperty(Type, String, BindingFlags) GetProperty(Type, String, BindingFlags) GetProperty(Type, String, BindingFlags) GetProperty(Type, String, BindingFlags)
GetProperty(Type, String, Type) GetProperty(Type, String, Type) GetProperty(Type, String, Type) GetProperty(Type, String, Type)
GetProperty(Type, String, Type, Type[]) GetProperty(Type, String, Type, Type[]) GetProperty(Type, String, Type, Type[]) GetProperty(Type, String, Type, Type[])
IsAssignableFrom(Type, Type) IsAssignableFrom(Type, Type) IsAssignableFrom(Type, Type) IsAssignableFrom(Type, Type)
IsInstanceOfType(Type, Object) IsInstanceOfType(Type, Object) IsInstanceOfType(Type, Object) IsInstanceOfType(Type, Object)

Aplica-se a

Veja também