且构网

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

测试对象是否为 C# 中的泛型类型

更新时间:2023-02-09 16:07:48

如果你想检查它是否是泛型类型的实例:

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

return list.GetType().IsGenericType;

如果你想检查它是否是一个通用的List:

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

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

正如 Jon 所指出的,这会检查确切的类型等价性.返回 false 并不一定意味着 list 是 List 返回 false(即对象不能分配给 List 变量).

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).