Accessing a Collection Through Reflection

前端 未结 9 2150
时光说笑
时光说笑 2020-12-14 00:39

Is there a way to iterate (through foreach preferably) over a collection using reflection? I\'m iterating over the properties in an object using reflection, and when the pr

9条回答
  •  情书的邮戳
    2020-12-14 01:26

    I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. string for instance is also IEnumerable and will iterate over the characters.

    Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable).

        public bool isCollection(object o)
        {
            return typeof(ICollection).IsAssignableFrom(o.GetType())
                || typeof(ICollection<>).IsAssignableFrom(o.GetType());
        }
    

提交回复
热议问题