• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

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();
        }
    }
}

结果:

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

 

原文链接

 

posted @ 2022-07-04 21:08  PowerCoder  阅读(2460)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3