欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 动态获取代码所在行号

程序员文章站 2022-08-27 08:34:17
通过System.Diagnostics.StackTrace获取代码所在行号和文件信息获取行号信息 /// /// Get line number of code dynamically /// /// number of frames to skip /// line number of cod... ......

通过system.diagnostics.stacktrace获取代码所在行号和文件信息

获取行号信息

        /// <summary>
        /// get line number of code dynamically
        /// </summary>
        /// <param name="skipframes">number of frames to skip</param>
        /// <returns>line number of code after skipping frames</returns>
        public static int getcodelinenum(int skipframes)
        {
            stacktrace st = new stacktrace(skipframes, true);
            stackframe fram = st.getframe(0);
            int linenum = fram.getfilelinenumber();
            return linenum;
        }

skipframes == 0 :

获取的是 system.diagnostics.stacktrace st = new system.diagnostics.stacktrace(skipframes, true); 所在行号

skipframes == 1:

获取的是函数getcodelinenum被调用时所在行号


获取文件路径信息

        /// <summary>
        /// get file name information of code dynamically
        /// </summary>
        /// <param name="skipframes">number of frames to skip</param>
        /// <returns>file name information of code after skipping frames</returns>
        public static string getcodefilename(int skipframes)
        {
            stacktrace st = new stacktrace(skipframes, true);
            stackframe fram = st.getframe(0);
            string source = fram.getfilename();
            return source;
        }

获取exception中行号

int linenum = ex.stacktrace.indexof("行号");