我正在学习 .net 反射,并且很难理解它的区别。
据我了解,List<T>
是一种通用类型定义。这是否意味着对于 .net 反射来说,T 就是通用类型?
具体地说,我想更多地了解 Type.IsGenericType 和 Type.IsGenericTypeDefinition 函数的背景知识。
谢谢!
我正在学习 .net 反射,并且很难理解它的区别。
据我了解,List<T>
是一种通用类型定义。这是否意味着对于 .net 反射来说,T 就是通用类型?
具体地说,我想更多地了解 Type.IsGenericType 和 Type.IsGenericTypeDefinition 函数的背景知识。
谢谢!
List<T>
是一个泛型类型定义。 T
被称为泛型类型参数。当类型参数像List<string>
或List<int>
或List<double>
这样指定时,你就有了一个泛型类型。你可以通过运行以下代码来查看:...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);
}
这将会打印出来
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.
直接获取泛型类型定义的另一种方法是使用 typeof(List<>)
或者 typeof(Dictionary<,>)
。
这可能会有所帮助:
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.");
}
如果你运行它,你会发现第一个测试通过了,因为两个项目都实现了类型List<T>
。第二个测试失败了,因为List<string>
和List<int>
不同。泛型类型定义是在定义T
之前比较原始的泛型。
IsGenericType
类型只是检查泛型T
是否已经定义。IsGenericTypeDefinition
检查泛型T
是否未定义。如果您想知道两个对象是否从相同的基本泛型类型定义中定义,例如第一个List<T>
示例,则这非常有用。