Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c# - Determine if collection is of type IEnumerable<T>

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

Code:

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

Output:

NS.1.Program+<GetInts>d__0

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

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

And this returns 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>)));
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you mean the collection, then just as:

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

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

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

if(typeof(IEnumerable<int>).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<T> for any T - otherwise check t.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...