C# 如何获取当前函数的名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10130504/
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-09 12:34:00 来源:igfitidea点击:
How to get the name of current function?
提问by Hyman
Possible Duplicate:
Can you use reflection to find the name of the currently executing method?
C# how to get the name of the current method from code
For example:
例如:
void foo() {
Console.Write(__MYNAME__);
}
print: foo
打印: foo
it's possible do it in C#?
可以在 C# 中做到吗?
采纳答案by Rapha?l Althaus
Try this:
尝试这个:
System.Reflection.MethodBase.GetCurrentMethod().Name
回答by Albin Sunnanbo
You can check the stack trace
您可以检查堆栈跟踪
using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();
// get calling method name
Console.WriteLine(stackTrace.GetFrame(0).GetMethod().Name);
But beware, if the method is inlined you get the parent method name.
但请注意,如果该方法是内联的,您将获得父方法名称。

