正在关注 this question ,为什么 enumerable
在这里:
Type type = typeof(List<string>);
bool enumerable = (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>));
返回false
?
编辑1
由于上述方法不起作用,确定类是否实现 IEnumerable 的最佳方法是什么?
最佳答案
在这里,我可能会使用 GetListType(type)
并检查 null
:
static Type GetListType(Type type) {
foreach (Type intType in type.GetInterfaces()) {
if (intType.IsGenericType
&& intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
return intType.GetGenericArguments()[0];
}
}
return null;
}
关于c# - 在 List<T> 中查找 IEnumerable<T> 时,GetGenericTypeDefinition 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1908918/