原文地址: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: }
更多文章見:守望軒[http://www.watch-life.net/]