我想从内部获取方法名称。这可以使用reflection
完成,如下所示。但是,我想在不使用reflection
的情况下得到它
System.Reflection.MethodBase.GetCurrentMethod().Name
示例代码
public void myMethod()
{
string methodName = // I want to get "myMethod" to here without using reflection.
}
从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
的使用。
正如您所说,您不想使用反射,那么您可以使用System.Diagnostics
获取方法名称,如下所示:
using System.Diagnostics;
public void myMethod()
{
StackTrace stackTrace = new StackTrace();
// get calling method name
string methodName = stackTrace.GetFrame(0).GetMethod().Name;
}
注意:反射比堆栈跟踪方法快得多。