Determine if collection is of type IEnumerable

后端 未结 9 2025
轻奢々
轻奢々 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:29

    Same technique as Marc's answer, but Linqier:

    namespace NS
    {
        class Program
        {
            static IEnumerable GetInts()
            {
                yield return 1;
            }
    
            static void Main()
            {
                var i = GetInts();
                var type = i.GetType();
                var isEnumerableOfT = type.GetInterfaces()
                    .Any(ti => ti.IsGenericType
                         && ti.GetGenericTypeDefinition() == typeof(IEnumerable<>));
                Console.WriteLine(isEnumerableOfT);
            }
        }
    }
    

提交回复
热议问题