2010-04-02 17 views
17

Sto studiando su .net reflection e sto avendo difficoltà a capire la differenza.Qual è la differenza tra un tipo generico e una definizione di tipo generico?

Da quello che ho capito, List<T> è una definizione di tipo generico. Significa che per .net reflection T è il tipo generico?

In particolare, credo che sto cercando più di fondo sulle funzioni Type.IsGenericType e Type.IsGenericTypeDefinition.

Grazie!

risposta

25

Nell'esempio List<T> è una definizione di tipo generico. T è chiamato parametro di tipo generico. Quando il parametro type è specificato come in List<string> o List<int> o List<double>, si ha un tipo generico. Si può vedere che con l'uso di alcuni codice come questo ...

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);  
} 

che stamperà

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. 

Un altro modo per ottenere la definizione di tipo generico direttamente è typeof(List<>) o typeof(Dictionary<,>).

+0

Ahhhh e tutto ha senso ora – Micah

+0

Grande spiegazione. – wonde

2

Ciò contribuirà a spiegarlo forse:

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."); 
} 

Se lo si esegue si otterrà la prima prova da superare, perché entrambi gli elementi stanno attuando il tipo List<T>. Il secondo test non riesce perché List<string> non corrisponde a List<int>. La definizione del tipo generico sta confrontando il generico originale prima che sia definito T.

Il tipo IsGenericType sta solo controllando se è stato definito il generico T. IsGenericTypeDefinition controlla che il generico T NON sia stato definito. Ciò è utile se vuoi sapere se due oggetti sono stati definiti dallo stesso tipo generico di base come il primo esempio List<T>.

Problemi correlati