#if 使您可以開始條件指令,測試一個或多個符號以查看它們是否計算為 true。如果它們的計算結果確實為true,則編譯器將計算位於 #if 與最近的 #endif 指令之間的所有代碼。例如,
1 #if DEBUG
2 string file = root + "/conf_debug.xml";
3 #else
4 string file = root + "/conf.xml";
5 #endif
這段代碼會像往常那樣編譯,但讀取debug配置文件包含在#if子句內。這行代碼只有在前面的#define命令定義了符號DEBUG后才執行。當編譯器遇到#if語句后,將先檢查相關的符號是否存在,如果符號存在,就只編譯#if塊中的代碼。否則,編譯器會忽略所有的代碼,直到遇到匹配的#endif指令為止。一般是在調試時定義符號DEBUG,把不同的調試相關代碼放在#if子句中。在完成了調試后,就把#define語句注釋掉,所有的調試代碼會奇跡般地消失,可執行文件也會變小,最終用戶不會被這些調試信息弄糊塗(顯然,要做更多的測試,確保代碼在沒有定義DEBUG的情況下也能工作)。這項技術在C和C++編程中非常普通,稱為條件編譯(conditional compilation)。
參考msdn實例:
1 // preprocessor_if.cs
2 #define DEBUG
3 #define VC_V7
4 using System;
5 public class MyClass
6 {
7 static void Main()
8 {
9 #if (DEBUG && !VC_V7)
10 Console.WriteLine("DEBUG is defined");
11 #elif (!DEBUG && VC_V7)
12 Console.WriteLine("VC_V7 is defined");
13 #elif (DEBUG && VC_V7)
14 Console.WriteLine("DEBUG and VC_V7 are defined");
15 #else
16 Console.WriteLine("DEBUG and VC_V7 are not defined");
17 #endif
18 }
19 }
輸出結果:
DEBUG and VC_V7 are defined