I've found this to be the most reliable way to determine the element type of a collection.įinally if that doesn't work, we look for IEnumerable and if we find it, we return the object type. If that doesn't bear fruit, next we query for IList and if we find it, we look for a public indexer property that takes a single integer parameter, and returns some type other than object.įinally, if we can't find that, we look for ICollection, and look for an Add() method with a single parameter that is not of type object. If we find it, we return DictionaryEntry. The first thing we do is query for the IDictionary interface. Easy peasy, and it works on dictionaries, too.įor getting a non-generic collection element type, we must use some heuristics, unfortunately. NET post 1.1, but prior to that, there was no standard interface for typed collections, due to the impossibility of creating a generic interface that could handle that.įor getting a generic collection type, all we do is query for the IEnumerable interface and then return whatever T is, in this case. I typically run into this while writing code generators. We may sometimes need to get the element type of a collection through reflection. Getting the element type is far more involved for these collections. For example, much of Windows Forms as well as the CodeDOM have typed collections like this. These collections are surprisingly common. This will be the case with typed collections that were created before. What may seem relatively easy at first quickly becomes complicated where typed collections are involved that do not implement IEnumerable. With this tip, I will endeavor to show you, gentle reader, how to use reflection to query a collection class for its element type.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |