测试对象是否为 C# 中的泛型类型
问题描述:
我想测试一个对象是否是泛型类型.我尝试了以下但没有成功:
I would like to perform a test if an object is of a generic type. I've tried the following without success:
public bool Test()
{
List<int> list = new List<int>();
return list.GetType() == typeof(List<>);
}
我做错了什么,我该如何进行这个测试?
What am I doing wrong and how do I perform this test?
答
如果你想检查它是否是泛型类型的实例:
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).