private void WriteLog() 
        {
            Trace.Listeners.Clear();
            DefaultTraceListener MyListener = new DefaultTraceListener();
            Trace.Listeners.Add(MyListener);
            Debugger.Log(2, "Test", "This  is  a  test");
            Console.ReadLine();  
        }
 
这时会向输出窗口输出 This is a test 
 
        private void WriteLog() 
        {
            Debugger.Log(2, "Test", "This  is  a  test");
            Console.ReadLine();  
        }

 

这时也会向输出窗口输出 This is a test
那我为什么还要实例化一个MyListener呢?查询MSDN上有这么一段话:
由于 DefaultTraceListener 会自动包含在每个 Listeners 集合中并且是唯一自动包含的侦听器,因此该行为是 Debug 和 Trace 消息的默认行为。
是不是可以理解为debugger中已包含 DefaultTraceListener 默认可以不写?

经过与我兄弟两人在网上的查找,终于找到了一个让我满意的结果:

http://www.dotnet247.com/247reference/articles/0/4526.aspx

Summary:
When using Debug and Trace messages in your application, the output messages are sent to any Listener object defined in the Listeners collection. When debugging and tracing is enabled, a default listener class called DefaultTraceListener is automatically created and initialized. The DefaultTraceListener object will output any messages received to the Output window if you're running your application in Visual Studio .NET, under debug mode.

也就是说DefaultTraceListener 会随Debug 和 Trace 自动创建和初始化,也就是说采用第二种方式是正确的

posted on 2007-05-25 13:51  forrestsun  阅读(751)  评论(0编辑  收藏  举报