2010-04-02 191 views
17

我.NET的反射学习起来,我有一个很难搞清楚的差异。泛型类型和泛型类型定义有什么区别?

从我个人理解,List<T>是泛型类型定义。这是否意味着.net反射T是泛型?

具体来说,我想我正在寻找在Type.IsGenericType和Type.IsGenericTypeDefinition功能更多的背景。

谢谢!

回答

25

在您的例子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);  
} 

,它将打印

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. 

另一种方式来获得泛型类型定义是直接typeof(List<>)typeof(Dictionary<,>)

+0

Ahhhh现在一切都合情合理 – Micah 2010-04-02 03:02:10

+0

很好的解释。 – wonde 2010-04-02 03:05:46

2

这将有助于也许解释:

List<string> lstString = new List<string>(); 
List<int> lstInt = new List<int>(); 

if (lstString.GetType().GetGenericTypeDefinition() == 
    lstInt.GetType().GetGenericTypeDefinition()) 
{ 
    Console.WriteLine("Same type definition."); 
} 

if (lstString.GetType() == lstInt.GetType()) 
{ 
    Console.WriteLine("Same type."); 
} 

如果你运行它,你会得到第一个测试通过,因为这两个项目正在实施类型List<T>。第二次测试失败,因为List<string>是不一样的List<int>。泛型类型定义是在定义T之前比较原始泛型。

IsGenericType类型只是检查是否已定义通用TIsGenericTypeDefinition检查以确定通用T尚未定义。如果您想知道两个对象是否已从相同的基本泛型类型(例如第一个List<T>示例)定义,这非常有用。