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#自動定義了

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


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

Example

 1}


執行結果(Debug Mode)

(原創) 使用preprocessor directive留住debug code (.NET) (C#)Could not find file 'D:\__Clare\CSharp\CSharpLab\bin\Debug\ReadMe.txt'.
(原創) 使用preprocessor directive留住debug code (.NET) (C#)請按任意鍵繼續 . . .


執行結果(Release Mode)

(原創) 使用preprocessor directive留住debug code (.NET) (C#)請按任意鍵繼續 . . .


26到33行

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


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

相关文章:

  • 2021-08-22
  • 2022-01-18
  • 2021-06-23
  • 2021-10-13
  • 2022-01-16
  • 2021-08-06
  • 2022-01-05
  • 2021-12-15
猜你喜欢
  • 2022-03-08
  • 2021-09-27
  • 2022-02-04
  • 2021-10-19
  • 2021-07-31
  • 2021-07-19
  • 2021-11-28
相关资源
相似解决方案