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#中List<>与List<String>之间的关系,包括如何获取类型定义及泛型参数。
6658

被折叠的 条评论
为什么被折叠?



