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

2021-06-17 03:04

阅读:528

标签:file   etc   exce   ppi   mic   static   函数   动态获取   add   

通过System.Diagnostics.StackTrace获取代码所在行号和文件信息

获取行号信息

        /// 
        /// Get line number of code dynamically
        /// 
        /// number of frames to skip
        /// line number of code after skipping frames
        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被调用时所在行号


获取文件路径信息

        /// 
        /// Get file name information of code dynamically
        /// 
        /// number of frames to skip
        /// file name information of code after skipping frames
        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("行号");

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

标签:file   etc   exce   ppi   mic   static   函数   动态获取   add   

原文地址:https://www.cnblogs.com/lyh523329053/p/10338559.html


评论


亲,登录后才可以留言!