C# 如何在不使用C中的反射的情况下从方法内部获取方法名#
我想从内部获取方法名。这可以使用C# 如何在不使用C中的反射的情况下从方法内部获取方法名#,c#,methods,system.reflection,C#,Methods,System.reflection,我想从内部获取方法名。这可以使用反射来完成,如下所示。但是,我不想使用反射 System.Reflection.MethodBase.GetCurrentMethod().Name 示例代码 public void myMethod() { string methodName = // I want to get "myMethod" to here without using reflection. } 正如您所说,您不想使用反射,那么您可以使用System.Diagnost
反射来完成,如下所示。但是,我不想使用反射
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;
}
注意:反射比堆栈跟踪方法快得多
从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
的使用。谢谢你的帮助answer@BandaraKamal乔恩·斯基特的回答比我好。他还提供了最新C#版本的参考资料。所以考虑接受他的回答,谢谢C 6的参考。