How can I find the method that called the current method?

后端 未结 19 1717
猫巷女王i
猫巷女王i 2020-11-21 22:50

When logging in C#, how can I learn the name of the method that called the current method? I know all about System.Reflection.MethodBase.GetCurrentMethod(), but

19条回答
  •  甜味超标
    2020-11-21 22:56

    /// 
    /// Returns the call that occurred just before the "GetCallingMethod".
    /// 
    public static string GetCallingMethod()
    {
       return GetCallingMethod("GetCallingMethod");
    }
    
    /// 
    /// Returns the call that occurred just before the the method specified.
    /// 
    /// The named method to see what happened just before it was called. (case sensitive)
    /// The method name.
    public static string GetCallingMethod(string MethodAfter)
    {
       string str = "";
       try
       {
          StackTrace st = new StackTrace();
          StackFrame[] frames = st.GetFrames();
          for (int i = 0; i < st.FrameCount - 1; i++)
          {
             if (frames[i].GetMethod().Name.Equals(MethodAfter))
             {
                if (!frames[i + 1].GetMethod().Name.Equals(MethodAfter)) // ignores overloaded methods.
                {
                   str = frames[i + 1].GetMethod().ReflectedType.FullName + "." + frames[i + 1].GetMethod().Name;
                   break;
                }
             }
          }
       }
       catch (Exception) { ; }
       return str;
    }
    

提交回复
热议问题