The product name is Widget
The available units on hand are 100
The per unit cost is 1.03
Debug Information-Product Ending
Trace Information-Product Starting
The product name is Widget
Field: The product name is Widget
This message WILL appear
Trace Information-Product Ending
Output.txt 位於專案 \bin 目錄 (通常 C:\Documents and Settings\User\My Documents\Visual Studio Projects\conInfo\bin)。
using System;
using System.Diagnostics;
using System.IO;
class Class1
{
[STAThread]
static void Main(string[] args)
{
string sProdName = "Widget";
int iUnitQty = 100;
double dUnitCost = 1.03;
Debug.WriteLine("Debug Information-Product Starting ");
Debug.Indent();
Debug.WriteLine("The product name is " + sProdName);
Debug.WriteLine("The available units on hand are " + iUnitQty);
Debug.WriteLine("The per unit cost is " + dUnitCost);
System.Xml.XmlDocument oxml = new System.Xml.XmlDocument();
Debug.WriteLine(oxml);
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, "Field");
Debug.WriteLine("Total Cost is " + (iUnitQty * dUnitCost), "Calc");
Debug.WriteLineIf(iUnitQty > 50, "This message WILL appear");
Debug.WriteLineIf(iUnitQty < 50, "This message will NOT appear");
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);
Debug.WriteLine("The product name is " + sProdName);
Debug.WriteLine("The available units on hand are " + iUnitQty);
Debug.WriteLine("The per unit cost is " + dUnitCost);
Debug.Unindent();
Debug.WriteLine("Debug Information-Product Ending");
Debug.Flush();
Trace.WriteLine("Trace Information-Product Starting ");
Trace.Indent();
Trace.WriteLine("The product name is " + sProdName);
Trace.WriteLine("The product name is " + sProdName, "Field");
Trace.WriteLineIf(iUnitQty > 50, "This message WILL appear");
Trace.Assert(dUnitCost > 1, "Message will NOT appear");
Trace.Unindent();
Trace.WriteLine("Trace Information-Product Ending");
Trace.Flush();
Console.ReadLine();
}
}
Debug / Trace 共用 WriteLine、WriteLineIf、Indent/Unindent、Assert、Flush。Indent/Unindent 讓輸出分組易讀。WriteLineIf 條件式輸出;Assert 條件為 false 才輸出。TextWriterTraceListener 導向 Console 與檔案雙通道。Flush() 確保緩衝區寫入完成。DEBUG/TRACE 條件編譯符號才生效。