Accessing a Collection Through Reflection

前端 未结 9 2133
时光说笑
时光说笑 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:25

    If you're not using an instance of the object but rather a Type, you can use the following:

    // type is IEnumerable
    if (type.GetInterface("IEnumerable") != null)
    {
    }
    
    0 讨论(0)
  • 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());
        }
    
    0 讨论(0)
  • 2020-12-14 01:30

    I would look at the Type.FindInterfaces method. This can filter out the interfaces implemented by a given type. As in PropertyInfo.PropertyType.FindInterfaces(filterMethod, filterObjects). You can filter by IEnumerable and see if any results are returned. MSDN has a great example in the method documentation.

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