Type.GetGenericTypeDefinition Метод

Определение

Возвращает объект Type, представляющий определение универсального типа, на основе которого можно сконструировать текущий универсальный тип.

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

Возвращаемое значение

Type

Объект Type, представляющий универсальный тип, на основе которого можно сконструировать текущий тип.

Исключения

Текущий тип не является универсальным. То есть IsGenericType возвращает false.

Вызванный метод не поддерживается в базовом классе. Реализацию должны обеспечивать производные классы.

Примеры

В следующем примере кода создается экземпляр сконструированного типа с помощью обычного создания экземпляра, а затем используются GetType GetGenericTypeDefinition методы и для получения сконструированного типа и определения универсального типа. В этом примере используется универсальный Dictionary<TKey,TValue> тип; сконструированный тип представляет Dictionary<TKey,TValue> коллекцию Test объектов со строковыми ключами.

using namespace System;
using namespace System::Reflection;
using namespace System::Collections::Generic;

public ref class Test
{
public:
   static void Main()
   {
      Console::Write( L"\r\n--- Get the generic type that " );
      Console::WriteLine( L"defines a constructed type." );
     
      // Create a Dictionary of Test objects, using strings for the
      // keys.
      Dictionary< String^,Test^ >^ d = gcnew Dictionary< String^,Test^ >;
      
      // Get a Type object representing the constructed type.
      //
      Type^ constructed = d->GetType();
      DisplayTypeInfo( constructed );
      Type^ myGeneric = constructed->GetGenericTypeDefinition();
      DisplayTypeInfo( myGeneric );
   }

private:
   static void DisplayTypeInfo( Type^ t )
   {
      Console::WriteLine( L"\r\n{0}", t );
      Console::WriteLine( L"\tIs this a generic type definition? {0}",
         t->IsGenericTypeDefinition );
      Console::WriteLine( L"\tIs it a generic type? {0}",
         t->IsGenericType );
      array<Type^>^typeArguments = t->GetGenericArguments();
      Console::WriteLine( L"\tList type arguments ({0}):",
         typeArguments->Length );
      System::Collections::IEnumerator^ myEnum =
         typeArguments->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         Type^ tParam = safe_cast<Type^>(myEnum->Current);
         Console::WriteLine( L"\t\t{0}", tParam );
      }
   }
};

int main()
{
   Test::Main();
}

/* 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
 */
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
 */
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
'

Комментарии

Определение универсального типа — это шаблон, из которого могут быть созданы другие типы. например, из определения универсального типа G<T> (выраженного в синтаксисе C#; G(Of T) в Visual Basic или generic <typename T> ref class G в C++) можно создать и создать экземпляр типа G<int> ( G(Of Integer) в Visual Basic). При наличии Type объекта, представляющего этот сконструированный тип, GetGenericTypeDefinition метод возвращает определение универсального типа.

Если два сконструированных типа создаются из одного определения универсального типа с использованием одних и тех же аргументов типа, GetGenericTypeDefinition метод возвращает один и тот же Type объект для обоих типов.

При вызове GetGenericTypeDefinition метода для Type объекта, который уже представляет определение универсального типа, он возвращает текущий объект Type .

Важно!

Массив универсальных типов не является универсальным. в коде C# A<int>[] v; или коде Visual Basic Dim v() As A(Of Integer) тип переменной v не является универсальным. Используйте IsGenericType , чтобы определить, является ли тип универсальным перед вызовом GetGenericTypeDefinition .

Список неизменяемых условий для терминов, используемых в отражении универсальных типов, см. в примечаниях к описанию свойства IsGenericType.

Применяется к

См. также раздел