Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get collection of methods with the same name

I've got some code (for helping with url routing) that tries to find an action method in a controller.

My controller looks like so:

public ActionResult Item(int id)
{
    MyViewModel model = new MyViewModel(id);
    return View(model);
}

[HttpPost]
public ActionResult Item(MyViewModel model)
{
    //do other stuff here
    return View(model);
}

The following code attempts to find a method matching the url action:

//cont is a System.Type object representing the controller
MethodInfo actionMethod = cont.GetMethod(action);

Today this code threw a System.Reflection.AmbiguousMatchException: Ambiguous match found which makes sense given my two methods have the same name.

I took a look at the available methods of the Type object and found public MethodInfo[] GetMethods(); which seems to do what I want, except there doesn't seem to be an overload for searching for a method with a specific name.

I could just use this method and search everything it returns, but I'm wondering if there's another (simpler) way to obtain a list of all methods in a class with a specific name, when there are multiple.

like image 603
Mansfield Avatar asked May 29 '13 13:05

Mansfield


3 Answers

There's nothing wrong with searching through the result of GetMethods really, but if you really wanted to, you could do:

var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;

var myOverloads = typeof(MyClass)
                  .GetMember("OverloadedMethodName", MemberTypes.Method, flags)
                  .Cast<MethodInfo>();

...which uses this method. You may need to change the binding-flags as per your requirements.

I checked reference-source and found that this internally relies on a cached-multimap keyed by member-name (see RuntimeType.GetMemberList), so it should be somewhat more efficient than searching in client code each time.

You could also do (more convenient but slightly less efficient, in theory at least):

var myOverloads = typeof(MyClass).GetMember("OverloadedMethodName")
                                 .OfType<MethodInfo>();
like image 184
Ani Avatar answered Nov 10 '22 11:11

Ani


Just Get the Collection of Methods with GetMethods() amd filter them by using a Lambda Expression: GetMethods().Where(p => p.Name == "XYZ").ToList();

like image 45
Johannes Wanzek Avatar answered Nov 10 '22 11:11

Johannes Wanzek


Use

cont.GetMethod(action, new [] {typeof(MyViewModel )})
like image 22
vborutenko Avatar answered Nov 10 '22 11:11

vborutenko