Determine if collection is of type IEnumerable

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

How to determine if object is of type IEnumerable ?

Code:

namespace NS {
    class Program {
        static IEnumerable GetInts()         


        
9条回答
  •  萌比男神i
    2020-12-13 00:27

    I believe the best way to solve this should be simple.. You first write code that returns the generic arguments (or argument in your case) of the IEnumerable then write another line to make a comparison of the argument type you desire to compare to the type contained in the IEnumerable object (int, in your case). I have an example that displays two simple functions that handles both tasks.

        public static Type GetEnumerableArgumentType(Type type)
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                return type.GetGenericArguments()[0];
            else
                return null;            
        }        
    
        public static bool EnumerableContainsArgumentType(Type tEnumerable, Type tGenArg)
        {
            return GetEnumerableArgumentType(tEnumerable) == tGenArg;
        }
    

提交回复
热议问题