【问题标题】:How to get the name of current function? [duplicate]如何获取当前函数的名称? [复制]
【发布时间】:2012-04-25 04:59:38
【问题描述】:

可能重复:
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# 实现吗?

【问题讨论】:

  • 在 .Net 4.5 中,您可以使用 CallerMemberNameAttribute 来获取调用者的姓名。请参阅msdn.microsoft.com/en-us/library/… ...然后您可以将函数的主体包装在匿名函数中,如 ([CallerMemberName] string functionName = "")=>{ }。在接受的答案中使用反射方法的问题是(1)函数可能被内联,和/或(2)如果函数名称是非公开的并且代码被混淆,则函数名称可能被混淆。

标签: c# .net system.reflection


【解决方案1】:

您可以检查堆栈跟踪

using System.Diagnostics;

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

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

但请注意,如果方法是内联的,您将获得父方法名称。

【讨论】:

    【解决方案2】:

    试试这个:

    System.Reflection.MethodBase.GetCurrentMethod().Name 
    

    【讨论】:

    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 2011-04-17
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多