C# - glance over the Type and related to Generic

You may wonder if List<> is the same type as List<String> and what is the relation between those Two. Here is some example to show you how to find the relationship between the two and what you can do to get the real generic type arguments. 

class Program
  {
    static void Main(string[] args)
    {
      // 
      List<string> listOfString = new List<string>();
      Type type = typeof(List<>);
      Type type2 = listOfString.GetType();
      Console.WriteLine("typeof(List<>) == typeof(List<string>) == {0}", type == type2);
      Console.WriteLine("Type(List<string>) is generic type: {0}", type2.IsGenericType);
      Console.WriteLine("Type(List<>) is generic type: {0}", type.IsGenericType);
      Type genericDefinition = type2.GetGenericTypeDefinition();
      Console.WriteLine("Type(List<string>).GetGeneircTypeDefinition == typeof<List<T>) = {0}", genericDefinition == type);
      var genericArguments = type2.GetGenericArguments();
      int i = 0;
      foreach (var item in genericArguments)
      {
        Console.WriteLine("Type(List<string>): Generic Argument {0}: {1}", ++i, item.Name);
      }
    }
  }

 

For better discussion of hte C# generics, you may find information above. 

你可能感兴趣的:(C#)