Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

.net - What is the difference between a generic type and a generic type definition?

I'm Studying up on .net reflection and am having a hard time figuring out the difference.

From what I understand, List<T> is a generic type definition. Does that mean that to .net reflection T is the generic type?

Specifically, I guess I'm looking for more background on the Type.IsGenericType and Type.IsGenericTypeDefinition functions.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your example List<T> is a generic type definition. T is called a generic type parameter. When the type parameter is specified like in List<string> or List<int> or List<double> then you have a generic type. You can see that by running some code like this...

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

Which will print

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.

Another way to get the generic type definition directly is typeof(List<>) or typeof(Dictionary<,>).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...