2008-11-11 44 views
5

停课时"How can I find the method that called the current method?"你如何找到来电功能?

精确复制是this可以用C#?

void main() 
{ 
    Hello(); 
} 

void Hello() 
{ 
    // how do you find out the caller is function 'main'? 
} 
+0

http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-c​​alled-the-current-method? – 2008-11-11 09:30:01

+0

此问题是[http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-c​​alled-the-current-method](http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-c​​alled-the-current-method) – 2008-11-11 09:30:59

回答

17
Console.WriteLine(new StackFrame(1).GetMethod().Name); 

然而,这并不健壮,尤其是作为的优化(如JIT内联)可与所感知的堆栈帧猴。

+0

嗨,马克。由于JIT,是否有可能在运行期间改变方法名称? – Joe 2012-03-14 13:50:08

3

here

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1); 
System.Diagnostics.StackFrame sf = st.GetFrame(0); 
string msg = sf.GetMethod().DeclaringType.FullName + "." + 
sf.GetMethod().Name; 
MessageBox.Show(msg); 

但也有一句话,这无法与多线程工作。