Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Collection Through Reflection

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 program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.

At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?

like image 900
Bob Wintemberg Avatar asked Sep 19 '08 19:09

Bob Wintemberg


People also ask

What is reflection explain its use with example?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is System reflection?

Reflection is the process of describing the metadata of types, methods and fields in a code. The namespace System.Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods and value types. Some of the commonly used classes of System.Reflection are: Class.


1 Answers

I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that.

if (item is IEnumerable) {     foreach (object o in (item as IEnumerable))     {      } } else {    // reflect over item } 
like image 141
Darren Kopp Avatar answered Oct 07 '22 16:10

Darren Kopp