我想从内部获取方法名称。可以使用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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句