条件编译指令有以下四种:
●#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
本文来自编程入门网:http://www.bianceng.cn/Programming/csharp/200709/4406.htm