代码之家  ›  专栏  ›  技术社区  ›  Storm

如何在运行时从方法中查找调用方法的方法名?

  •  0
  • Storm  · 技术社区  · 15 年前

    如何在运行时从方法中找到调用方法的方法名?

    例如:

    Class A
    {
        M1()
        {
            B.M2();
        }
    }
    
    class B
    {
        public static M2()
        {
            // I need some code here to find out the name of the method that
            // called this method, preferably the name of the declared type
            // of the calling method also.
        }
    }
    
    5 回复  |  直到 11 年前
        1
  •  10
  •   Thomas Zoechling    15 年前

    你可以试试:

    using System.Diagnostics;
    
    StackTrace stackTrace = new StackTrace();
    Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
    
        2
  •  1
  •   James    15 年前

    我想你在找:

    using System.Diagnostics;
    
    StackTrace stackTrace = new StackTrace();
    stackTrace.GetFrame(1).GetMethod().Name;
    
        3
  •  0
  •   SimSimY    15 年前

    检查system.diagnostics.trace类,但据我所知-在那里 使用时的性能价格

        4
  •  0
  •   Community CDub    8 年前

    最好不要使用stackframe,因为存在一些.NET安全问题。如果代码不完全可信,表达式“new stackframe()”将引发安全异常。

    要获取当前方法,请使用:

    MethodBase.GetCurrentMethod().Name

    关于获取调用方法,请参见堆栈溢出问题 Object creation, how to resolve "class-owner"? .

        5
  •  0
  •   Peter Mortensen icecrime    11 年前

    您可以通过显示调用堆栈来做到这一点,如下面的代码所示。这将找到整个调用堆栈,而不仅仅是调用方法。

    void displaycallstack() {
        byte[] b;
        StackFrame sf;
        MemoryStream ms = new MemoryStream();
        String s = Process.GetCurrentProcess().ProcessName;
        Console.Out.WriteLine(s + " Call Stack");
        StackTrace st = new StackTrace();
        for (int a = 0;a < st.FrameCount; a++) {
            sf = st.GetFrame(a);
            s = sf.ToString();
            b = Encoding.ASCII.GetBytes(s);
            ms.Write(b,0,b.Length); 
        }
        ms.WriteTo(System.Console.OpenStandardOutput());
    }