如何通过辅助方法打印当前执行的方法名?

How to print the current executing method name via an auxiliary method?

ExecutingMethodName 用于打印调用方的方法名称。例如:

static class Auxiliary
{
    public static void ExecutingMethodName()
    {
        Console.WriteLine(new StackFrame(0).GetMethod().Name);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Auxiliary.ExecutingMethodName();// should print Main
    }
    static void Foo()
    {
        Auxiliary.ExecutingMethodName();// should print Foo
    }    
}

问题

上面的当前实现总是打印 ExecutingMethodName 这不是我想要的。如何通过辅助方法打印当前执行的方法名?

只需将您方法中的堆栈框架调用中的 0 更改为 1(StackFrame(0) 是您在调用堆栈中的当前位置,您需要向后退一步):

public static void ExecutingMethodName()
{
    Console.WriteLine(new StackFrame(1).GetMethod().Name);
}

使用下面的代码。您必须使用 StackFrame(1)StackFrame(2) 将始终是 ExecutingMethodName,实际上您必须打印 ExecutingMethodName.

的调用者
public static void ExecutingMethodName()
        {
            Console.WriteLine(new StackFrame(1).GetMethod().Name);
        }

可以参考StackFrame Constructor (Int32)

在 C# 5 中它变得更容易了。

CallerMemberNameAttribute

您必须跳过堆栈帧中的第一个条目(属于 ExecutingMethodName):

public static void ExecutingMethodName()
{
    Console.WriteLine(new StackFrame(1).GetMethod().Name);
}

使用 CallerMemberNameAttribute 而不是使用堆栈框架中的内容。更简洁的方式。

public static void ExecutingMethodName([CallerMemberName]string callerName= null)
{
    Console.WriteLine(callerName);
}