.NET反思:检测的IEnumerable< T>IEnumerable、NET、GT、LT

2023-09-03 02:29:24 作者:抱歉"您的爱不在服务区

我试图来检测,如果一个类型对象的特定实例是一个通用的IEnumerable的......

I'm trying to detect if a particular instance of a Type object is a generic "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)

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

But this seems a bit indirect - is there a more direct/elegant way to do this?

推荐答案

您可以使用

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

编辑:添加的IsGenericType检查,感谢您的有益意见

added the IsGenericType check, thanks for the useful comments