泛型类型和泛型类型定义有什么区别?

Mic*_*cah 20 .net generics reflection

我正在研究.net反思,我很难搞清楚差异.

据我所知,List<T>是一种通用的类型定义.这是否意味着.net反射T是泛型类型?

具体来说,我想我正在寻找有关Type.IsGenericType和Type.IsGenericTypeDefinition函数的更多背景知识.

谢谢!

Jas*_*yon 30

在您的示例中List<T>是泛型类型定义. T被称为泛型类型参数.当类型参数被指定为List<string>或者List<int>或者List<double>你有一个泛型类型.您可以通过运行这样的代码来看到...

public static void Main()
{
    var l = new List<string>();
    PrintTypeInformation(l.GetType());
    PrintTypeInformation(l.GetType().GetGenericTypeDefinition());
}

public static void PrintTypeInformation(Type t)
{
    Console.WriteLine(t);
    Console.WriteLine(t.IsGenericType);
    Console.WriteLine(t.IsGenericTypeDefinition);    
}
Run Code Online (Sandbox Code Playgroud)

哪个会打印

System.Collections.Generic.List`1[System.String] //The Generic Type.
True //This is a generic type.
False //But it isn't a generic type definition because the type parameter is specified
System.Collections.Generic.List`1[T] //The Generic Type definition.
True //This is a generic type too.                               
True //And it's also a generic type definition.
Run Code Online (Sandbox Code Playgroud)

另一种直接获取泛型类型定义的方法是typeof(List<>)typeof(Dictionary<,>).