Web Developer tips (83): obtains the name of the called method from the stack through reflection.

Source: Internet
Author: User

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/]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.