Determine if collection is of type IEnumerable

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

    You can use the is keyword.

    [TestFixture]
    class Program
    {
        static IEnumerable<int> GetInts()
        {
            yield return 1;
        }
    
        [Test]
        static void Maasd()
        {
            var i = GetInts();
            Assert.IsTrue(i is IEnumerable<int>);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 00:29

    Same technique as Marc's answer, but Linqier:

    namespace NS
    {
        class Program
        {
            static IEnumerable<int> 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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 00:30

    Try

    type.GetInterface("IEnumerable") != null && type.IsGenericType

    0 讨论(0)
提交回复
热议问题