且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果测试的对象是通用型的C#

更新时间:2023-02-09 15:29:42

如果您要检查它是否是一个泛型类型的实例:

If you want to check if it's an instance of a generic type:

return list.GetType().IsGenericType;

如果您要检查它是否是一个普通的名单,其中,T>

If you want to check if it's a generic List<T>:

return list.GetType().GetGenericTypeDefinition() == typeof(List<>);

正如乔恩所指出的,这个检查的确切类型等价。返回不一定意味着列表清单&LT; T&GT; 返回(即对象不能被分配​​到一个名单,其中,T&GT; 变量)。

As Jon points out, this checks the exact type equivalence. Returning false doesn't necessarily mean list is List<T> returns false (i.e. the object cannot be assigned to a List<T> variable).