c# 如何获取当前方法的调用堆栈(转载)
c# 调试程序时常常需要借助 call stack 查看调用堆栈,实际上通过code也可以获取:
using System; using System.Diagnostics; namespace Stack { 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); } Console.WriteLine("Full stack info:"); Console.WriteLine(stacktrace.ToString()); return num1 + num2; } } }
结果: