你如何找到呼叫者function?

作为“如何找到调用当前方法的方法?”的精确副本关闭。

这可能与c#有关吗?

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

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

然而,这并不健壮,尤其是因为优化(例如JIT内联)可以与感知的堆栈帧一起使用。

从这里 :

 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 ); 

但也有人说这不适用于multithreading。