c# 如何获取当前方法的调用堆栈

c# 调试程序时常常需要借助 call stack 查看调用堆栈,实际上通过code也可以获取:

    class Program
    {
        static void Main(string[] args)
        {
            Test();
        }

        private static void Test()
        {
            var result = Sum(1, 2);
        }

        private static int Sum(int num1, int num2)
        {
            var stacktrace = new StackTrace();
            for (var i = 0; i < stacktrace.FrameCount; i++)
            {
                var method = stacktrace.GetFrame(i).GetMethod();
                Console.WriteLine(method.Name); }
return num1 + num2; } }

结果:

posted @ 2019-12-07 22:07  内心澎湃的水晶侠  阅读(4190)  评论(0编辑  收藏  举报