.NET反思:检测的IEnumerable&LT; T&GT; [英] .NET Reflection: Detecting IEnumerable<T>
本文介绍了.NET反思:检测的IEnumerable&LT; T&GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图来检测,如果一个类型对象的特定实例是一个通用的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
这篇关于.NET反思:检测的IEnumerable&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文