c# - 确定集合是否属于 IEnumerable<T> 类型

标签 c# .net linq collections types

如何判断对象是否为IEnumerable类型?

代码:

namespace NS {
    class Program {
        static IEnumerable<int> GetInts() {
            yield return 1;
        }
        static void Main() {
            var i = GetInts();
            var type = i.GetType();
            Console.WriteLine(type.ToString());
        }
    }
}

输出:

NS.1.Program+<GetInts>d__0

如果我将 GetInts 更改为返回 IList,则一切正常 输出是:

 System.Collections.Generic.List`1[System.Int32]

这会返回 false:

namespace NS {
    class Program {
        static IEnumerable<int> GetInts() {
            yield return 1;
        }
        static void Main() {
            var i = GetInts();
            var type = i.GetType();
            Console.WriteLine(type.Equals(typeof(IEnumerable<int>)));
        }
    }
}

最佳答案

如果您指的是集合,那么就是as :

var asEnumerable = i as IEnumerable<int>;
if(asEnumerable != null) { ... }

但是,我假设(根据示例)您有一个 Type :

对象 永远不会是“属于”类型 IEnumerable<int> - 但它可能实现它;我希望:

if(typeof(IEnumerable<int>).IsAssignableFrom(type)) {...}

会做。如果您不知道 T (上面的 int),然后检查所有实现的接口(interface):

static Type GetEnumerableType(Type type) {
    if (type.IsInterface && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        return type.GetGenericArguments()[0];
    foreach (Type intType in type.GetInterfaces()) {
        if (intType.IsGenericType
            && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {
            return intType.GetGenericArguments()[0];
        }
    }
    return null;
}

并调用:

Type t = GetEnumerableType(type);

如果为空,则不是 IEnumerable<T>对于任何 T - 否则检查 t .

关于c# - 确定集合是否属于 IEnumerable<T> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1846671/

相关文章:

c# - 使用窗口内的自定义关闭按钮关闭 kendoui 窗口

.net - 项目和程序集命名约定

c# - 如何禁用 WPF 窗口上的 HitTest ?

c# - 显示没有断点的当前调用堆栈

c# - 动态 Linq to 实体排序与分页

c# - 请求的服务尚未注册! AutoFac 依赖注入(inject)

c# - Xna 内容管道扩展 - 在自定义处理器中加载其他内容

c# - 创建一个任务列表,包含任务但不执行

c# - IEnumerable<string> 到字符串

c# - 哪个 LINQ 语句对于使用 Entity Framework 搜索记录有效