How to get a method name from a known method?

Is it possible to get the name of another method in the same class, but without using a manually written string?

class MyClass { private void doThis() { // Wanted something like this print(otherMethod.name.ToString()); } private void otherMethod() { } } 

You may ask why: well, the reason is that I have to call the method later, like this Invoke ("otherMethod"), but I donโ€™t want to hardcode this line, because I cannot reorganize it within the project.

+6
source share
4 answers

One approach is that you can transfer it to an Action delegate, then you can access the method name:

 string name = new Action(otherMethod).Method.Name; 
+8
source

You can use reflection (an example is http://www.csharp-examples.net/get-method-names/ ) to get the names of the methods. Then you can search for the method that you are looking for by name, parameters, or even use the attribute for its tag.

But the real question is: are you sure this is what you need? It looks like you really don't need to think, but you need to think about your design. If you already know which method you are going to call, why do you need this name? How about using a delegate? Or exposing a method through an interface and storing a reference to some class that implements it?

+2
source

Try the following:

 MethodInfo method = this.GetType().GetMethod("otherMethod"); object result = method.Invoke(this, new object[] { }); 
+1
source

Btw. I also found (in the internet extension) an alternative solution just to get the method string. It also works with parameters and return types:

 System.Func<float, string> sysFunc = this.MyFunction; string s = sysFunc.Method.Name; // prints "MyFunction" public string MyFunction(float number) { return "hello world"; } 
0
source

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


All Articles