Optimized way to get "get_Item" MethodInfo
Asked Answered
W

2

6

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

Is there anything better?

Worldshaking answered 10/2, 2011 at 0:18 Comment(0)
L
6

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.

Legato answered 10/2, 2011 at 0:25 Comment(2)
I want the MethodInfo, not the PropertyInfo.Worldshaking
@smartcaveman: Wow. Use PropertyInfo.GetGetMethod on what I have given you above.Legato
P
2

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.

Projectile answered 10/2, 2011 at 6:55 Comment(2)
Do you have any documentation for this? I can't find it anywhere.Worldshaking
MSDN, look at the VB.NET Default keyword and the DefaultMemberAttribute class.Projectile

© 2022 - 2024 — McMap. All rights reserved.