我该如何确定C#泛型类型的无参数类型以进行检查?

5

是否有可能检查泛型类型,而不使用任何泛型参数?

例如,我想能够执行类似于以下操作(实际类型名称已更改以保护隐私):

var list = new List<SomeType>();

...

if (list is List)
    {
    Console.WriteLine("That is a generic list!");
    }

上述代码当前生成以下错误:
Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments

有什么解决方法吗?最好是简洁的,适用于没有泛型参数的类型(例如:“如果myString是List”)的方法。
1个回答

9

你可以这样检查:

var type = list.GetType();
if(type.IsGenericType && 
   type.GetGenericTypeDefinition().Equals(typeof(List<>)))
{
    // do work
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接