C# 你如何找到调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/280413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:24:00  来源:igfitidea点击:

How do you find the caller function?

c#language-featurescallstack

提问by Serhat Ozgel

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

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

Is thispossible with c#?

是否可能与C#?

void main()
{
   Hello();
}

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

采纳答案by Marc Gravell

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 内联)可能会与感知到的堆栈帧发生冲突。

回答by schnaader

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.

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