web developer tips (83):通过反射从堆栈里获取调用的方法名称

原文地址:You can get the name of the calling method from the stack using reflection

几乎每个程序都需要一个日志来记录事件、错误和异常。有时候,在记录的事件里的方法名是很有用的,最简单的做法就是写一个“方法”,这个“方法”使用两个参数:调用的方法名和事件
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:  }

在这个例子中,每个方法在调用的时候都需要指出它的名称。除此外,如果方法名改变了,开发者需要知道。然而,这里有个简洁的方法得到调用方法的名称,就是通过堆栈获取。因为栈顶的方法是当前被正在执行的方法,所以调用方法将是正确的。据此,可以通过跟踪实例堆栈(注意不要忘记包含System.Diagnostics)和得到frame第一索引值,得到一个来自调用方法中与StackFrame相对应的调用,最后使用反射(reflection )得到方法名。

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:  }


微信扫描下方的二维码阅读本文

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注