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

2023-09-02 11:47:12 作者:倾心之夏

我想进行测试,如果对象是一个泛型类型。我已经尝试了以下没有成功:

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;

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

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

 
精彩推荐
图片推荐