学会使用Trace和Debug

本文介绍了如何使用Trace和Debug工具来输出程序状态并捕获错误,以提高程序的健壮性和可调试性。详细解释了Trace和Debug的区别,并展示了实际代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随着我们程序的逐渐庞大,业务逻辑的逐渐复杂,我们写的代码往往,或者说越来越不按照我们预料的方式运行。碰到这样的情况,通常我们会使用Debugger来调试我们的程序。但是,Debugger不是万能的。我们程序里会有总多的线程,会有很多的循环,这样情况下,会使调试变的非常麻烦,我们也会很头疼。
于是,通过使用Trace或Debug,我们会将程序的状态输出到消息记录(EvengLog)上来,通过查看消息记录,我们便多了一条解决问题的路径,从而使的我们的程序更加的Robust!
1.NameSpace
System.Diagnostics
2.简介
这两个类都提供了一些方法,通过使用这些方法,你可以输出一些程序的状态,抛出一个错误之类的。
两者不同的地方,Trace可以在程序运行的时候使用,而Debug只能在调试的时候使用。就是说,通过调用Trace的方法输出消息,在程序运行的时候仍然可以捕获到这些消息。而Debug输出的消息,只有在调试的时候才能够看到。
3.Trace类定义
不直接写了,直接看定义。
这里也不翻译了,英文也比较简单易懂。

Method

Description

Assert (condition, message)

Displays the specified string message when the condition provided to the method evaluates to false. When you do not specify the message text, the Call Stack is displayed instead.

Fail (message)

Similar to the Assert() method, this writes the specified text to the Call Stack when a failure occurs. The Assert() method differs because Fail() cannot specify a condition before displaying the error. In fact, the Fail() method is usually placed in the catch statement of a try-catch-finally instruction. You could also place it anywhere in your code that you are sure could never be reached - such as in the default case of a switch statement where you believe you've allowed for all possibilities.

Write (message | object)

Writes the specified text message, or object name, to the listener application.

WriteIf (condition, message)

Writes the specified message text into the listener application if the specified condition is true.

WriteLine (message | object)

Writes the specified message text, or object name, followed by a carriage return.

WriteLineIf (condition, message)

Writes the specified message text followed by a carriage return if the specified condition is true.

4.如何消除Trace和Debug
当你的程序想要发布的时候,你无须亲自手动将这些Trace,Debug的调用语句删掉。通过下图的配置,编译器会自动的将这些调用语句删除。



5. 如何使用Trace/Debug
使用这两个类很简单。
首先,这两个类提供了Static方法,这就意味着你无须自己去创建instance。
 1 static void Main()
 2    {
 3      Trace.WriteLine("Entered Main()");
 4 
 5      for (int i = 0; i < 6; i++)
 6        Trace.WriteLine(i);
 7 
 8      Trace.WriteLine("Exiting from Main()");
 9    }
10 
编译这样的程序,通过Visual Studio的Output窗口,你就能够看到:


转载于:https://www.cnblogs.com/xiaxili/archive/2008/06/17/1224275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值