C# #if, #else和#endif预处理指令

    #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的情况下也能工作)。这项技术在CC++编程中非常普通,称为条件编译(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




posted @ 2012-04-06 15:42  Peter.Luo  阅读(13500)  评论(5编辑  收藏  举报