Debug.WriteLine("The product name is " + sProdName, "Field");
Debug.WriteLine("The units on hand are " + iUnitQty, "Field");
Debug.WriteLine("The per unit cost is " + dUnitCost.ToString(), "Field");
Debug.WriteLine("Total Cost is " + (iUnitQty * dUnitCost), "Calc");
輸出格式:Category: Message (例:Field: The product name is Widget)。
Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");
第一參數為條件,第二參數為條件 true 時輸出的訊息。
Debug.Assert(dUnitCost > 1, "Message will NOT appear");
Debug.Assert(dUnitCost < 1, "Message will appear since dUnitcost < 1 is false");
TextWriterTraceListener tr1 = new TextWriterTraceListener(Console.Out);
Debug.Listeners.Add(tr1);
TextWriterTraceListener tr2 = new TextWriterTraceListener(File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);
tr1 導向主控台,tr2 導向檔案。
Debug.Unindent();
Debug.WriteLine("Debug Information-Product Ending");
Debug.Flush();
Indent/Unindent 搭配產生巢狀縮排,便於閱讀。Flush() 強制將緩衝區資料寫入所有 Listener。Trace 與 Debug 共享:WriteLine、WriteLineIf、Indent、Unindent、Assert、Flush。差異在條件編譯符號 (DEBUG vs TRACE)。