web developer tips (83):通過反射從堆棧裡擷取調用的方法名稱

來源:互聯網
上載者:User

原文地址: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/]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.