2009-07-22 62 views
3

可能重複:
How can I find the method that called the current method?C#方法調用者

嗨, 我怎樣才能確定從方法中的一個方法的調用者?例如:

SomeNamespace.SomeClass.SomeMethod() { 
    OtherClass(); 
} 

OtherClass() { 
    // Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod 
} 

感謝

+4

杜佩 - http://stackoverflow.com/問題/ 171970/how-can-i-find-the-method-that-c​​alled-the-current-method和http://stackoverflow.com/questions/280413/c-how-do-you-find-the-調用者函數關閉 – William 2009-07-22 06:47:42

回答

6

這些文章應該是幫助:

  1. http://iridescence.no/post/GettingtheCurrentStackTrace.aspx
  2. http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx

基本上,代碼如下所示:

StackFrame frame = new StackFrame(1); 
MethodBase method = frame.GetMethod(); 
message = String.Format("{0}.{1} : {2}", 
method.DeclaringType.FullName, method.Name, message); 
Console.WriteLine(message); 
+5

小心點。我被這個bug一次抓住了。如果您構建您的應用程序以進行發佈,則該方法可以嵌入並且您的堆棧跟蹤看起來會有所不同。 – Anish 2013-01-09 18:23:15

1

您需要從MSDN使用StackTrace

片段

// skip the current frame, load source information if available 
StackTrace st = new StackTrace(new StackFrame(1, true)) 
Console.WriteLine(" Stack trace built with next level frame: {0}", 
    st.ToString()); 
1

可以使用System.Diagnostics.StackTrace類:

StackTrace stackTrace = new StackTrace();   // get call stack 
    StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) 

    // write call stack method names 
    foreach (StackFrame stackFrame in stackFrames) 
    { 
    Console.WriteLine(stackFrame.GetMethod().Name); // write method name 
    }