What is the difference between a generic type and a generic type definition?

前端 未结 2 1800
天涯浪人
天涯浪人 2020-12-09 09:32

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

From what I understand, List is a generic type defi

2条回答
  •  萌比男神i
    2020-12-09 10:16

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

    public static void Main()
    {
        var l = new List();
        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<,>).

提交回复
热议问题