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
How do you find the caller function?
提问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.
但也有评论说这不适用于多线程。