Original article address: You can get the name of the calling method from the stack Using Reflection
Almost every program needs a log to record events, errors, and exceptions. Sometimes, the method name in the recorded event is very useful. The simplest way is to write a "method". This "method" uses two parameters: the called method name and the event.
Http://www.watch-life.net/visual-studio/you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.html
[C #]
1: void Log(string callingMethodName, string eventMessage)2: {3: Console.WriteLine("Event logged by " + callingMethodName);4: Console.WriteLine("Event: " + eventMessage);5: 6: }
In this example, each method must specify its name when calling it. In addition, developers need to know if the method name has changed. However, here is a simple method to get the name of the called method, which is obtained through the stack. The method at the top of the stack is the method currently being executed, so it is correct to call the method. Therefore, you can trace the instance stack (do not forget to include system. diagnostics) and get the first index value of the frame, get a call from the call method corresponding to stackframe, and finally use reflection to get the method name.
01: using System.Diagnostics;02: 03: void Log(string eventMessage)04: { 05: 06: Console.WriteLine("Event logged by " + (new StackTrace()).GetFrame(1).GetMethod().Name); 07: 08: Console.WriteLine("Event: " + eventMessage);09: 10: }
For more articles, see: Watch Xuan [http://www.watch-life.net/]