Compartilhar via


Type.GetGenericTypeDefinition Método

Definição

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

public:
 abstract Type ^ GetGenericTypeDefinition();
public:
 virtual Type ^ GetGenericTypeDefinition();
public abstract Type GetGenericTypeDefinition();
public virtual Type GetGenericTypeDefinition();
abstract member GetGenericTypeDefinition : unit -> Type
abstract member GetGenericTypeDefinition : unit -> Type
override this.GetGenericTypeDefinition : unit -> Type
Public MustOverride Function GetGenericTypeDefinition () As Type
Public Overridable Function GetGenericTypeDefinition () As Type

Retornos

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

Exceções

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

Não há suporte para o método invocado na classe base. 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 o e GetGenericTypeDefinition os GetType métodos para recuperar o tipo construído e a definição de tipo genérico. Este exemplo usa o tipo genérico Dictionary<TKey,TValue> ; o tipo construído representa um Dictionary<TKey,TValue> dos objetos com chaves de Test cadeia de caracteres.

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
 */
open System
open System.Collections.Generic

type Test() = class end

let displayTypeInfo (t: Type) =
    printfn $"\n{t}"
    printfn $"\tIs this a generic type definition? {t.IsGenericTypeDefinition}"
    printfn $"\tIs it a generic type? {t.IsGenericType}"
    let typeArguments = t.GetGenericArguments()
    printfn $"\tList type arguments ({typeArguments.Length}):"
    for tParam in typeArguments do
        printfn $"\t\t{tParam}"

printfn "\n--- Get the generic type that defines a constructed type."

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

// Get a Type object representing the constructed type.
let constructed = d.GetType()
displayTypeInfo constructed

let generic = constructed.GetGenericTypeDefinition()
displayTypeInfo generic


(* 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
 *)
Imports System.Reflection
Imports System.Collections.Generic

Public Class Test
    Public Shared Sub Main() 
        Console.WriteLine(vbCrLf & "--- Get the generic type that defines a constructed type.")
        
        ' Create a Dictionary of Test objects, using strings for the
        ' keys.
        Dim d As New Dictionary(Of String, Test)
        
        ' Get a Type object representing the constructed type.
        '
        Dim constructed As Type = d.GetType()
        DisplayTypeInfo(constructed)
        
        Dim generic As Type = constructed.GetGenericTypeDefinition()
        DisplayTypeInfo(generic)
    End Sub
    
    Private Shared Sub DisplayTypeInfo(ByVal t As Type) 
        Console.WriteLine(vbCrLf & t.ToString())
        Console.WriteLine(vbTab & "Is this a generic type definition? " _
            & t.IsGenericTypeDefinition)
        Console.WriteLine(vbTab & "Is it a generic type? " _
            & t.IsGenericType)
        Dim typeArguments As Type() = t.GetGenericArguments()
        Console.WriteLine(vbTab & "List type arguments (" _
            & typeArguments.Length & "):")
        For Each tParam As Type In typeArguments
            Console.WriteLine(vbTab & vbTab & tParam.ToString())
        Next tParam
    End Sub
End Class

' 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 G<T>de tipo genérico C#, você pode construir e instanciar o tipo G<int>. Dado um Type objeto que representa esse tipo construído, o GetGenericTypeDefinition método retorna a definição de tipo genérico.

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

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

Importante

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

Para obter uma lista das condições invariantes para termos usados na reflexão genérica, veja as observações da propriedade IsGenericType.

Aplica-se a

Confira também