是否可以在不使用任何通用参数的情况下检查泛型类型?
例如,我希望能够做类似以下的事情(实际类型的名称已被更改以保护无辜者):
var list = new List<SomeType>();
...
if (list is List)
{
Console.WriteLine("That is a generic list!");
}
Run Code Online (Sandbox Code Playgroud)
上面的代码当前生成以下错误:
Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments
Run Code Online (Sandbox Code Playgroud)
有没有解决的办法?优选地,简洁的东西以及不具有通用参数的类型的东西(即:"if myString is List").
你可以这样检查:
var type = list.GetType();
if(type.IsGenericType &&
type.GetGenericTypeDefinition().Equals(typeof(List<>)))
{
// do work
}
Run Code Online (Sandbox Code Playgroud)