如何在不使用C#中的反射的情况下从该方法中获取方法名称

问题描述 投票:6回答:2

我想从内部获取方法名称。这可以使用reflection完成,如下所示。但是,我想在不使用reflection的情况下得到它

System.Reflection.MethodBase.GetCurrentMethod().Name 

示例代码

public void myMethod()
{
    string methodName =  // I want to get "myMethod" to here without using reflection. 
}
c# methods system.reflection
2个回答
24
投票

从C#5开始,您可以让编译器为您填写,如下所示:

using System.Runtime.CompilerServices;

public static class Helpers
{
    public static string GetCallerName([CallerMemberName] string caller = null)
    {
        return caller;
    }
}

MyMethod

public static void MyMethod()
{
    ...
    string name = Helpers.GetCallerName(); // Now name=="MyMethod"
    ...
}

请注意,您可以通过显式传入值来错误地使用它:

string notMyName = Helpers.GetCallerName("foo"); // Now notMyName=="foo"

在C#6中,还有nameof

public static void MyMethod()
{
    ...
    string name = nameof(MyMethod);
    ...
}

但是,这并不保证您使用与方法名称相同的名称 - 如果使用nameof(SomeOtherMethod),它当然会具有"SomeOtherMethod"的值。但是如果你做对了,那么将MyMethod的名称重构为其他东西,任何半合半的重构工具都会改变你对nameof的使用。


6
投票

正如您所说,您不想使用反射,那么您可以使用System.Diagnostics获取方法名称,如下所示:

using System.Diagnostics;

public void myMethod()
{
     StackTrace stackTrace = new StackTrace();
     // get calling method name
     string methodName = stackTrace.GetFrame(0).GetMethod().Name;
}

注意:反射比堆栈跟踪方法快得多。

© www.soinside.com 2019 - 2024. All rights reserved.