2009-08-21 184 views
32

可能重複:
How can I find the method that called the current method?獲取從調用函數調用函數名

我怎樣才能從C#調用函數調用函數的名字嗎?

+1

重複http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-c​​alled-the-current-method – 2009-08-21 05:00:02

+2

這是一個騙局,但可能值得保持開放到不同的術語 - 可能有助於搜索人員。 – Keith 2009-08-21 13:27:08

+1

@Keith:是的,出於這個原因,我們通常會盡量避免重複問題,當他們以一種截然不同的方式被問到 - 這就是爲什麼關閉它們會自動在頂部添加鏈接的原因,以便未來的搜索者可以找到方法答案更快。 – Shog9 2009-08-21 18:28:08

回答

70
new StackFrame(1, true).GetMethod().Name 

注意,在發佈版本的編譯器可能會內聯該方法被調用,在這種情況下,上面的代碼將返回調用程序的調用程序,因此爲了安全起見你應該裝點你的方法:

[MethodImpl(MethodImplOptions.NoInlining)] 
+11

請注意,以這種方式走棧會帶來相當重的性能影響。我強烈建議在使用之前尋找一種不涉及堆棧散步的解決方案。 – jrista 2009-08-21 05:01:12

+1

由於提到了MethodImpl屬性,所以此答案實際上比重複問題中的答案要好。 – 2009-08-29 16:35:33

+8

我知道這是一個騙局,標籤爲.net 3.5,但爲了幫助那些第一次遇到這種情況的人(像我一樣),最好在你的回答中指出,在C#5.0中你現在可以使用所描述的調用者信息在:http://visualstudiomagazine.com/articles/2012/11/01/more-than-just-async.aspx – acarlon 2013-09-13 02:46:28

14

這將讓你,你是在方法的名字:

string currentMethod = System.Reflection.MethodBase.GetCurrentMethod().Name; 

使用謹慎,因爲有可能是一個性能命中。

To get callers: 
StackTrace trace = new StackTrace(); 
int caller = 1; 

StackFrame frame = trace.GetFrame(caller); 

string callerName = frame.GetMethod().Name; 

這使用堆棧散步來獲取方法名稱。調用者的價值是調用堆棧走多遠。小心不要走遠。

+0

我需要哪個方法調用當前的方法。 – Sauron 2009-08-21 05:11:57

+0

您從堆棧跟蹤中獲取調用者名稱的方式,是否會影響性能? – Panos 2014-10-29 13:33:46