如何在C#中不使用反射从方法内部获取方法名称

13
我希望从函数内部获取函数名。虽然可以使用反射来实现,但我想在不使用反射的情况下完成。

我希望从函数内部获取函数名。虽然可以使用reflection来实现,但我想在不使用reflection的情况下完成。

System.Reflection.MethodBase.GetCurrentMethod().Name 

示例代码

public void myMethod()
{
    string methodName =  // I want to get "myMethod" to here without using reflection. 
}
2个回答

38

从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


感谢提供 C# 6.0 的参考资料。 - Rahul Nikate

5

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

using System.Diagnostics;

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

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

感谢您的回答。 - Nishantha Bulumulla
@BandaraKamal Jon Skeet的回答比我更好。此外,他还引用了最新C#版本的参考资料。因此,请考虑接受他的答案。 - Rahul Nikate

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接