我怎样才能看到GenericTypeDefinition是否实现IEnumerable<> [英] How can I see if GenericTypeDefinition implements IEnumerable<>
本文介绍了我怎样才能看到GenericTypeDefinition是否实现IEnumerable<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法来检查一个类型是否为泛型,然后检查GenericTypeDefinition是否为 IEnumerable<>
。
I have a method that checks if a type is generic and then checks if the GenericTypeDefinition is of IEnumerable<>
.
static Type GetEnumerableType(Type type)
{
if(type.IsGenericType) {
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IEnumerable<>)) {
return type.GetGenericArguments()[0];
}
}
return null;
}
如果它是IEnumerable,它就像一个魅力一样。如果GenericTypeDefinition是 IList>
或 List>< / code>它不起作用。我试过..
Works like a charm if it is an IEnumerable. If the the GenericTypeDefinition is IList<>
or List<>
it doesn't work. I've tried..
typeof(IEnumerable<>).IsAssignableFrom(genericTypeDefinition)
..没有成功。当然,必须有更好的方法,然后链接else语句
..without success. Of course there must be a better way then chaining else-statements?
推荐答案
您可以使用 GetInterfaces
来检查类型是否实现 IEnumerable<>
像这样
You can use GetInterfaces
to check if a type implements IEnumerable<>
like so
Type type = new List<string>().GetType();
if (type.IsGenericType)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition.GetInterfaces()
.Any( t => t.IsGenericType &&
t.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
{
return type.GetGenericArguments()[0];
}
}
这篇关于我怎样才能看到GenericTypeDefinition是否实现IEnumerable<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文