條件編譯指令有以下四種:
●#if
●#elfi
●#else
●#endif
這些條件編譯指令用來有條件地將部分程序段包括進來或排除在外。它們和C#中的if語句有類似的作用。你可以在指令中使用邏輯操作符與(&&),或(||)和取反操作符(!)等。它們在程序中的出現的先後順序必須是這樣:
一條#if語句(必須有)
零或多條#elif語句
零或一條#else語句
一條#endif語句(必須有)
下面我們通過一些例子來說明它們的用法。
#define Debug
class Class1
{
#if Debug
void Trace(string s){}
}
再比如:
#define A
#define B
#undef C
class D
{
#if C
void F(){}
#elif A && B
void I(){}
#else
void G(){}
#endif
}
不難看出,它實際編譯的效果等同於:
class C
{
void I(){}
}
在這個例子裡,請大家注意#elif指令的使用,它的含義是:“else if”,使用#elif可以在#if指令中加入一個或多個分支。
#if指令可以嵌套使用,例如:
#define Debug //Debugging on
#undef Trace //Tracing off
class Purchase Transaction
{
void Commit(){
#if Debug
CheckConsistency();
#if Trace
WriteToLog(this.ToString());
#endif
#enfif
CommitHelper();
}
}
預處理指令如果出現在其它輸出輸出元素中間就不會被執行。例如下面的程序試圖在定義了Debug時顯示hello world,否則顯示hello everyone,但結果卻令人哭笑不得:
程序清單8-6:
using System;
class Hello
{
static void Main(){
System.Console.WriteLine(@"hello,
#if Debug
world
#else
everyone
#endif
");
}
}
該程序輸出結果如下:
hello,
#if Debug
world
#else
everyone
#endif