Ler em inglês

Compartilhar via


Type.GetGenericTypeDefinition Método

Definição

Retorna um objeto Type que representa uma definição de tipo genérico do qual o tipo genérico atual pode ser criado.

C#
public abstract Type GetGenericTypeDefinition ();
C#
public virtual Type GetGenericTypeDefinition ();

Retornos

Type

Um objeto Type que representa um tipo genérico do qual o tipo atual pode ser criado.

Exceções

O tipo atual não é um tipo genérico. Ou seja, IsGenericType retorna false.

O método chamado não é suportado na classe base. As classes derivadas devem fornecer uma implementação.

Exemplos

O exemplo de código a seguir cria uma instância de um tipo construído usando a criação de instância comum e, em seguida, usa os métodos e para recuperar o tipo construído e a GetType GetGenericTypeDefinition definição de tipo genérico. Este exemplo usa o tipo genérico; o tipo construído representa um de objetos Dictionary<TKey,TValue> com chaves de cadeia de Dictionary<TKey,TValue> Test caracteres.

C#
using System;
using System.Reflection;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        Console.WriteLine("\r\n--- Get the generic type that defines a constructed type.");

        // Create a Dictionary of Test objects, using strings for the
        // keys.       
        Dictionary<string, Test> d = new Dictionary<string, Test>();

        // Get a Type object representing the constructed type.
        //
        Type constructed = d.GetType();
        DisplayTypeInfo(constructed);

        Type generic = constructed.GetGenericTypeDefinition();
        DisplayTypeInfo(generic);
    }

    private static void DisplayTypeInfo(Type t)
    {
        Console.WriteLine("\r\n{0}", t);
        Console.WriteLine("\tIs this a generic type definition? {0}", 
            t.IsGenericTypeDefinition);
        Console.WriteLine("\tIs it a generic type? {0}", 
            t.IsGenericType);
        Type[] typeArguments = t.GetGenericArguments();
        Console.WriteLine("\tList type arguments ({0}):", typeArguments.Length);
        foreach (Type tParam in typeArguments)
        {
            Console.WriteLine("\t\t{0}", tParam);
        }
    }
}

/* This example produces the following output:

--- Get the generic type that defines a constructed type.

System.Collections.Generic.Dictionary`2[System.String,Test]
        Is this a generic type definition? False
        Is it a generic type? True
        List type arguments (2):
                System.String
                Test

System.Collections.Generic.Dictionary`2[TKey,TValue]
        Is this a generic type definition? True
        Is it a generic type? True
        List type arguments (2):
                TKey
                TValue
 */

Comentários

Uma definição de tipo genérico é um modelo do qual outros tipos podem ser construídos. Por exemplo, na definição de tipo genérico (expressa na sintaxe C#; no Visual Basic ou no G<T> G(Of T) generic <typename T> ref class G C++), você pode construir e criar uma instanência do tipo G<int> ( G(Of Integer) em Visual Basic). Dado um Type objeto que representa esse tipo construído, o método retorna a GetGenericTypeDefinition definição de tipo genérico.

Se dois tipos construídos são criados com a mesma definição de tipo genérico, usando os mesmos argumentos de tipo, o método retorna o GetGenericTypeDefinition mesmo objeto para ambos os Type tipos.

Se você chamar o GetGenericTypeDefinition método em um objeto que já representa uma definição de tipo Type genérico, ele retornará o Type atual.

Importante

Uma matriz de tipos genéricos não é genérica em si. No código C# A<int>[] v; ou no código Visual Basic , o tipo de Dim v() As A(Of Integer) variável não é v genérico. Use IsGenericType para determinar se um tipo é genérico antes de chamar GetGenericTypeDefinition .

Para obter uma lista das condições invariáveis para termos usados na reflexão genérica, consulte os comentários da propriedade IsGenericType.

Aplica-se a

Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Confira também