Can I get the name of the method by providing the method itself?

Is there a way to get the method name (as a string) by providing the method itself?

class Person { bool Eat(Food food){...} } 

I want to somehow get the line "Eat." All this! This can be either from an instance or from a class declaration using reflection.

My attempt:

 public delegate bool EatDelegate(Food f); EatDelegate eatDel = new EatDelegate(_person1.Eat); string methodName = eatDel.GetInvocationList()[0].Method.Name; 

This requires knowing the delegate of the method, and all this is unreadable

I need a method name to dynamically call it.

Notes:

  • There is a delegate declaration for every method I want to call
  • I want to avoid specifying a method name to avoid errors after reflection, etc.
  • The method is not called the moment when I want to get its name. (cannot use MethodBase.GetCurrentMethod() )
  • I need to use .Net 3.5
+4
source share
2 answers
 public string GetName(Expression<Action> exp) { var mce = exp.Body as MethodCallExpression; return mce.Method.Name; } 

-

a Method

 public int MyMethod(int i) { return 0; } 

and use

  var s= GetName(()=>this.MyMethod(0)); 
+5
source
 var methods = typeof(Person).GetMethods(); foreach (var method in methods) { if (method.Name.Equals("Eat")) { // do something here... } } 
0
source

Source: https://habr.com/ru/post/1438046/


All Articles