代码之家  ›  专栏  ›  技术社区  ›  Serhat Ozgel

如何找到调用者函数?[副本]

  •  5
  • Serhat Ozgel  · 技术社区  · 16 年前

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

    this

    void main()
    {
       Hello();
    }
    
    void Hello()
    {
      // how do you find out the caller is function 'main'?
    }
    
    2 回复  |  直到 8 年前
        1
  •  18
  •   Marc Gravell    16 年前
    Console.WriteLine(new StackFrame(1).GetMethod().Name);
    

    然而,这并不健壮,特别是当优化(如JIT内联)可能会和感知到的堆栈帧相混淆时。

        2
  •  3
  •   schnaader    16 年前

    从…起 here :

    System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
    System.Diagnostics.StackFrame sf = st.GetFrame(0);
    string msg = sf.GetMethod().DeclaringType.FullName + "." +
    sf.GetMethod().Name;
    MessageBox.Show( msg );
    

    但也有一种说法是,这不适用于多线程。

    推荐文章