Determine if collection is of type IEnumerable

后端 未结 9 2007
轻奢々
轻奢々 2020-12-12 23:50

How to determine if object is of type IEnumerable ?

Code:

namespace NS {
    class Program {
        static IEnumerable GetInts()         


        
9条回答
  •  温柔的废话
    2020-12-13 00:15

    If you mean the collection, then just as:

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

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

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

    if(typeof(IEnumerable).IsAssignableFrom(type)) {...}
    

    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;
    }
    

    and call:

    Type t = GetEnumerableType(type);
    

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

提交回复
热议问题