我有一个方法,检查类型是否是通用的,然后检查GenericTypeDefinition是否是IEnumerable<>.
static Type GetEnumerableType(Type type)
{
if(type.IsGenericType) {
var genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(IEnumerable<>)) {
return type.GetGenericArguments()[0];
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
如果它是一个IEnumerable,它就像一个魅力.如果GenericTypeDefinition是IList<>或List<>它不起作用.我试过了..
typeof(IEnumerable<>).IsAssignableFrom(genericTypeDefinition)
Run Code Online (Sandbox Code Playgroud)
..没有成功.当然必须有更好的方法然后链接其他语句?