【问题标题】:Can I find out the name of the method I am using?我可以找出我正在使用的方法的名称吗?
【发布时间】:2008-12-03 13:26:29
【问题描述】:

假设我有一些类似的代码

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

我可以找出我正在使用的方法的名称吗?在我的示例中,我想以编程方式将myMethodName 设置为当前方法的名称(即在本例中为"Portal.Author.SomeMethod")。

谢谢

【问题讨论】:

    标签: c# oop reflection


    【解决方案1】:
    MethodInfo.GetCurrentMethod().Name
    

    【讨论】:

    • 这很好用,但请记住在属性获取和设置等特殊方法中要小心。该名称看起来与特殊方法代码中的方法名称不完全相同。很容易去掉特殊部分。
    【解决方案2】:

    System.Reflection.MethodBase.GetCurrentMethod().Name

    【讨论】:

      【解决方案3】:

      MethodBase.GetCurrentMethod()

      【讨论】:

        【解决方案4】:

        System.DiagnosticsStackFrame/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】:

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

          所以

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

          【讨论】:

          • 但是您询问了方法名称。不是其他的,它们不是方法名称的一部分。
          • 您应该在问题的编辑中发布此内容,而不是作为答案。
          猜你喜欢
          • 2011-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多