如何在不使用 C# 反射的情况下从该方法内部获取方法名称
How to get method name from inside that method without using reflection in C#
我想从内部获取方法名称。这可以使用 reflection
来完成,如下所示。但是,我想在不使用 reflection
的情况下得到它
System.Reflection.MethodBase.GetCurrentMethod().Name
示例代码
public void myMethod()
{
string methodName = // I want to get "myMethod" to here without using reflection.
}
正如你所说,你不想使用反射,那么你可以使用 System.Diagnostics
来获取方法名称,如下所示:
using System.Diagnostics;
public void myMethod()
{
StackTrace stackTrace = new StackTrace();
// get calling method name
string methodName = stackTrace.GetFrame(0).GetMethod().Name;
}
Note : Reflection is far faster than stack trace method.
从 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
的使用。
我想从内部获取方法名称。这可以使用 reflection
来完成,如下所示。但是,我想在不使用 reflection
System.Reflection.MethodBase.GetCurrentMethod().Name
示例代码
public void myMethod()
{
string methodName = // I want to get "myMethod" to here without using reflection.
}
正如你所说,你不想使用反射,那么你可以使用 System.Diagnostics
来获取方法名称,如下所示:
using System.Diagnostics;
public void myMethod()
{
StackTrace stackTrace = new StackTrace();
// get calling method name
string methodName = stackTrace.GetFrame(0).GetMethod().Name;
}
Note : Reflection is far faster than stack trace method.
从 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
的使用。