Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimized way to get "get_Item" MethodInfo

Right now, I have: targetType.GetMethod("get_Item", BindingFlags.Instance)

Is there anything better?

like image 604
smartcaveman Avatar asked Feb 10 '11 00:02

smartcaveman


2 Answers

I prefer to use PropertyInfo.GetIndexParameters:

var indexers = targetType.GetProperties(bindingFlags)
                         .Where(p => p.GetIndexParameters().Any());
                         .Select(p => p.GetGetMethod());

Now indexers is an IEnumerable<MethodInfo> of the getters of the indexers that match the specified BindingFlags given in bindingFlags.

Note how the code reads like from the targetType, get the properties that match the bindingFlags, take those that are an indexer, and then project to the getter. It is much less mysterious than using the magic string "get_Item", and multiple indexers are handled easily.

If you know there is only one, you could of course use Single. If you are looking for a specific one of many, you can inspect the result of GetIndexParameters accordingly.

like image 191
jason Avatar answered Oct 15 '22 16:10

jason


The proper way is to retrieve the DefaultItemAttribute for the class. It has the name of the indexer property. It doesn't have to be "Item", languages like VB.NET allows specifying any property to be the indexer. Jason's code will also fail on them, there can be more than one indexed property. But only one default.

like image 31
Hans Passant Avatar answered Oct 15 '22 18:10

Hans Passant