c# 如何获取当前方法的调用堆栈(转载)
c# 调试程序时常常需要借助 call stack 查看调用堆栈,实际上通过code也可以获取:
using System.Diagnostics; using System.Reflection; namespace Net8StackInfoDemo { internal class Program { private static void Test() { var result = Sum(1, 2); } private static int Sum(int num1, int num2) { var stackTrace = new StackTrace(true); for (var i = 0; i < stackTrace?.FrameCount; i++) { StackFrame? stackFrame = stackTrace.GetFrame(i); MethodBase? stackMethod = stackFrame?.GetMethod(); string? stackFile = stackFrame?.GetFileName(); int? line = stackFrame?.GetFileLineNumber(); string stackLine = string.Format("{0} in {1} at line {2}", stackMethod?.Name, stackFile, line); Console.WriteLine(stackLine); } Console.WriteLine("Full stack info:"); Console.WriteLine(stackTrace?.ToString()); throw new Exception("Demo exception"); } static void Main(string[] args) { try { Test(); } catch (Exception e) { Console.WriteLine("Exception is {0}", e.GetType().ToString()); Console.WriteLine("Exception message is {0}", e.Message); Console.WriteLine("Exception stack is:\n{0}", e.StackTrace); } Console.WriteLine("Press any key to end..."); Console.ReadLine(); } } }
结果:

浙公网安备 33010602011771号