C#中打印出當前堆疊
阿新 • • 發佈:2019-02-13
使用C#過程中,除了通過try catch中的exception來列印當前的堆疊資訊,我們還可以主動通過System.DiagnosticsStackTrace這個類來主動打印出堆疊資訊。
程式碼:
結果:using System; using System.Diagnostics; namespace Test2 { class Program { static void Main(string[] args) { DebugInfo db = new DebugInfo(); Console.WriteLine(db.Test1()); } } class DebugInfo { public String Test1() { string info = null; //設定為true,這樣才能捕獲到檔案路徑名和當前行數,當前行數為GetFrames程式碼的函式,也可以設定其他引數 StackTrace st = new StackTrace(true); //得到當前的所以堆疊 StackFrame[] sf = st.GetFrames(); for (int i = 0; i < sf.Length; ++i) { info = info + "\r\n" + " FileName=" + sf[i].GetFileName() + " fullname=" + sf[i].GetMethod().DeclaringType.FullName + " function=" + sf[i].GetMethod().Name + " FileLineNumber=" + sf[i].GetFileLineNumber(); } return info; } } }
需要注意的是,無論是Debug還是Release模式,new StackTrace(true)的時候設定為true,並且exe路徑下存在pdb編譯資訊檔案,這才可以顯示當前路徑檔名和行數。