(原創) 使用preprocessor directive留住debug code (.NET) (C#)

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

 1/* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : Debug.cs
 5Compiler    : Visual Studio 2005 / C# 2.0
 6Description : Demo how to use preprocessor to debug
 7Release     : 07/10/2007 1.0
 8*/

 9using System;
10using System.IO;
11using System.Collections.Generic;
12
13class Client {
14  static bool fileToList(string fileName, List<string> list) {
15    StreamReader reader = null;
16
17    try {
18      reader = new StreamReader(fileName);
19      string line = reader.ReadLine();
20
21      while (line != null{
22        list.Add(line);
23        line = reader.ReadLine();
24      }

25    }

26    #if (DEBUG)
27    catch(Exception e) {
28      Console.WriteLine(e.Message);
29    #else
30    catch {
31    #endif
32      return false;
33    }

34    finally {
35      if (reader != null)
36        reader.Close();
37    }

38
39    return true;
40  }

41
42  static int Main(string[] args) {
43    string fileName = "ReadMe.txt";
44    List<string> list = new List<string>();
45
46    if (!fileToList(fileName, list))
47      return 1;
48
49    foreach (string line in list)
50      Console.WriteLine(line);
51
52    return 0;
53  }

54}


執行結果(Debug Mode)

Could not find file 'D:\__Clare\CSharp\CSharpLab\bin\Debug\ReadMe.txt'.
請按任意鍵繼續 . . .


執行結果(Release Mode)

請按任意鍵繼續 . . .


26到33行

#if (DEBUG)
  
catch(Exception e) {
  Console.WriteLine(e.Message);
#else
  
catch {
#endif
  
return false;
}


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

posted on 2007-07-10 23:26  真 OO无双  阅读(3780)  评论(6编辑  收藏  举报

导航