2010年6月23日 星期三

使用preprocessor directive留住debug code

Abstract
很多人以為debug mode和release mode的差異只是debug mode可以設Breakpoint而已,事實上,搭配preprocessor directive,debug mode另有妙用。

Introduction
preprocessor directive並不是什麼新東西,這在C語言就有的,如有些API在Windows 98和Windows XP不一樣,就得用preprocessor directive,讓不同的平台用不同的API。C#也可使用preprocessor directive,尤其用在debug時,非常方便。

我們常會有debug code,如try catch時,若有exception要顯示錯誤訊息,但真正發布產品時,則不希望顯示錯誤訊息,所以希望能留住debug code,以便日後debug,若用//或/* */的方式將debug code暫時當註解,常常遇到產品真正發布時,忘了將debug code拿掉的窘境,事實上,當使用debug mode時,C#自動定義了

#define DEBUG


所以我們可以用#if (DEBUG)來留住debug code。

Example
using System; using System.IO; using System.Collections.Generic; class Client { static bool fileToList(string fileName, List list) { StreamReader reader = null; try { reader = new StreamReader(fileName); string line = reader.ReadLine(); while (line != null) { list.Add(line); line = reader.ReadLine(); } } #if (DEBUG) catch(Exception e) { Console.WriteLine(e.Message); #else catch { #endif return false; } finally { if (reader != null) reader.Close(); } return true; } static int Main(string[] args) { string fileName = "ReadMe.txt"; List list = new List(); if (!fileToList(fileName, list)) return 1; foreach (string line in list) Console.WriteLine(line); return 0; } }


執行結果(Debug Mode)
Could not find file 'D:\__Clare\CSharp\CSharpLab\bin\Debug\ReadMe.txt'.
請按任意鍵繼續 . . .


執行結果(Release Mode)
請按任意鍵繼續 . . .


我們希望在debug mode時,能顯示exception message,但release mode時則不顯示,若用#if (DEBUG)來寫,再也不用擔心debug code忘記拿掉的問題,只要切換debug mode和release mode,就可輕鬆顯示debug code,而且Visual Studio 2005也會在切換debug和release時,動態改變code的顏色,讓你立刻知道哪些code會執行到。

Reference:
http://www.cnblogs.com/oomusou/archive/2007/07/10/813319.html

沒有留言:

張貼留言