确定集合是否属于 IEnumerable<T> 类型 [英] Determine if collection is of type IEnumerable&lt;T&gt;

查看:22
本文介绍了确定集合是否属于 IEnumerable<T> 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确定对象是否属于 IEnumerable 类型?

How to determine if object is of type IEnumerable <T>?

代码:

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,则一切正常输出是:

If I change GetInts to return IList, everything is OK the output is:

 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:

If you mean the collection, then just as:

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

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

However, I'm assuming (from the example) that you have a Type:

object 永远不会是of"的输入 IEnumerable - 但它可能实现它;我希望:

The object will never be "of" type IEnumerable<int> - but it might implement it; I would expect that:

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

会的.如果您不知道T(上面的int),请检查所有已实现的接口:

would do. If you don't know the T (int in the above), then check all the implemented interfaces:

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.

if this is null, it isn't IEnumerable<T> for any T - otherwise check t.

这篇关于确定集合是否属于 IEnumerable<T> 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆