Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在不使用C中的反射的情况下从方法内部获取方法名#_C#_Methods_System.reflection - Fatal编程技术网

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的参考。