使用 #if 以及 #else、#elif、#endif、#define 和 #undef 指令,可以包括或排除基于由一个或多个符号组成的条件的代码
一般条件编译用于你在调试的时候,需要输出结果来确定程序是否正确,但在发布的时候不需要输出这些结果。或者程序在某一版本发布了一个试用的功能,但在下一版本中要暂时去掉这个功能,就可以这个条件来控制。
#define DEBUG #define MYTEST using System; namespace ConsoleApplication1 { public class Class1 { public void Display() { #if (DEBUG && !MYTEST) Console.WriteLine("DEBUG is defined"); #elif (!DEBUG && MYTEST) Console.WriteLine("MYTEST is defined"); #elif (DEBUG && MYTEST) Console.WriteLine("DEBUG and MYTEST are defined"); #else Console.WriteLine("DEBUG and MYTEST are not defined"); #endif } } } using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Class1 cl = new Class1(); cl.Display(); #if DEBUG Console.WriteLine("123"); #endif } } }
结果
DEBUG and VC_V7 are defined
123