如何获取当前功能的名称?

时间:2012-04-12 19:34:19

标签: c# .net system.reflection

  

可能重复:
  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

例如:

void foo() {
    Console.Write(__MYNAME__);
}

打印:foo

可以在C#中实现吗?

2 个答案:

答案 0 :(得分:106)

试试这个:

System.Reflection.MethodBase.GetCurrentMethod().Name 

答案 1 :(得分:14)

您可以检查堆栈跟踪

using System.Diagnostics;

// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(0).GetMethod().Name);

但要注意,如果方法是内联的,则获取父方法名称。

相关问题