.NET反射:检测IEnumerable <T>

Pau*_*rth 11 .net generics reflection

我正在尝试检测Type对象的特定实例是否是通用的"IEnumerable"...

我能想到的最好的是:

// theType might be typeof(IEnumerable<string>) for example... or it might not
bool isGenericEnumerable = theType.GetGenericTypeDefinition() == typeof(IEnumerable<object>).GetGenericTypeDefinition()
if(isGenericEnumerable)
{
    Type enumType = theType.GetGenericArguments()[0];
    etc. ...// enumType is now typeof(string) 
Run Code Online (Sandbox Code Playgroud)

但这似乎有点间接 - 是否有更直接/更优雅的方式来做到这一点?

Ken*_* K. 22

您可以使用

if(theType.IsGenericType && theType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
    Type underlyingType = theType.GetGenericArguments()[0];
    //do something here
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了IsGenericType检查,感谢有用的评论

  • 这仅在'theType'恰好是typeof(IEnumerable <>)时才有效,而不是类型实现接口.希望这就是你所追求的. (3认同)
  • 如果theType不是通用的,它将抛出一个`InvalidOperationException` - 对于检查恕我直言不是一个非常好的解决方案. (2认同)