Get a set of methods with the same name

I have code (to help with URL routing) that is trying to find an action method in the controller.

My controller looks like this:

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 tries to find a method that matches the url action:

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

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

I looked at the available methods of the Type object and found public MethodInfo[] GetMethods(); which seems to do what I want, except that there is no overload for finding a method with a specific name.

I could just use this method and look for everything that it returns, but I'm wondering if there is another (simpler) way to get a list of all the methods in the class with a specific name when there are several.

+7
source share
3 answers

There is nothing wrong with finding 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 anchor flags to suit your requirements.

I checked the reference source and found that it internally depends on the cached multimap entered by the name key (see RuntimeType.GetMemberList), so it should be somewhat more efficient than searching the client code every time.

You can also do (more convenient, but slightly less efficient, at least theoretically):

 var myOverloads = typeof(MyClass).GetMember("OverloadedMethodName") .OfType<MethodInfo>(); 
+4
source

Just get a collection of methods using GetMethods() amd filter them using the Lambda expression: GetMethods().Where(p => p.Name == "XYZ").ToList();

+2
source

Using

 cont.GetMethod(action, new [] {typeof(MyViewModel )}) 
+1
source

All Articles