c# - 在 List<T> 中查找 IEnumerable<T> 时,GetGenericTypeDefinition 返回 false

标签 c# reflection list ienumerable

正在关注 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/

相关文章:

c# - EF6 - 没有做我对 .Any() 的预期

c# - 如何在 C# 中的后台线程上执行异步数据库调用

java - 使用反射从 Jar 文件中获取所有类

java - Android getDeclaredFields() 返回无序结果

python - 比较Python中的两个未知列表

python - 如何将值附加到字典中的列表值内

c# - 如何从方法 C# 中获取字符串值

C# 命令行项目 - 通过 .exe 运行时出错

通过堆栈跟踪的 Java 反射

python - 在 Python 中将两个列表合并为一个