你如何找到呼叫者功能? [重复]

时间:2022-09-02 09:31:56

Closed as exact duplicate of "How can I find the method that called the current method?"

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

Is this possible with c#?

这可能与c#有关吗?

void main()
{
   Hello();
}

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

2 个解决方案

#1


18  

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

However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.

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

#2


3  

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

But there is also a remark that this could not work with multi-threading.

但也有人说这不适用于多线程。

#1


18  

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

However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.

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

#2


3  

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

But there is also a remark that this could not work with multi-threading.

但也有人说这不适用于多线程。