代码之家  ›  专栏  ›  技术社区  ›  Ian G

我能找出我使用的方法的名称吗?

  •  3
  • Ian G  · 技术社区  · 16 年前

    比如我有一些代码

    namespace Portal
    {
      public class Author
        {
            public Author() { }
            private void SomeMethod(){
              string myMethodName = ""; 
              //  myMethodName = "Portal.Author.SomeMethod()";
            }
        }
    }
    

    我能找出我使用的方法的名称吗?在我的示例中,我希望以编程方式设置 myMethodName 当前方法的名称(在本例中为 "Portal.Author.SomeMethod" )

    谢谢

    5 回复  |  直到 16 年前
        1
  •  14
  •   leppie    16 年前
    MethodInfo.GetCurrentMethod().Name
    
        2
  •  3
  •   StingyJack    16 年前

    system.reflection.methodBase.getcurrentMethod().name

        3
  •  2
  •   Brian Genisio    16 年前

    方法库.getcurrentMethod())

        4
  •  2
  •   mookid8000    16 年前

    System.Diagnostics StackFrame / StackTrace 这就允许你这么做,包括更多。您可以这样检查整个调用堆栈:

    StackFrame stackFrame = new StackFrame(1, true); //< skip first frame and capture src info
    StackTrace stackTrace = new StackTrace(stackFrame);
    MethodBase method = stackTrace.GetMethod();
    string name = method.Name;
    
        5
  •  1
  •   Ian G    16 年前

    虽然@leppie让我走上了正确的道路,但它只给了我方法的名称,但是如果你看看我的问题,你会发现我想要包括名称空间和类信息…

    所以

    myMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType + 
                     "." + System.Reflection.MethodBase.GetCurrentMethod().Name;