所有的预处理器指令都是以 # 开始。且在一行上,只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句,所以它们不以分号(;)结束。

    C# 编译器没有一个单独的预处理器,但是,指令被处理时就像是有一个单独的预处理器一样。在 C# 中,预处理器指令用于在条件编译中起作用。与 C 和 C++ 不同的是,它们不是用来创建宏。一个预处理器指令必须是该行上的唯一指令。

    下表列出了 C# 中可用的预处理器指令:

    #define 预处理器指令创建符号常量。#define 允许您定义一个符号,这样,通过使用符号作为传递给 #if 指令的表达式,表达式将返回 true。它的语法如下:

    下面的程序说明了这点:

    1. using System;
    2. namespace PreprocessorDAppl
    3. {
    4. class Program
    5. {
    6. static void Main(string[] args)
    7. {
    8. #if (PI)
    9. Console.WriteLine("PI is defined");
    10. Console.WriteLine("PI is not defined");
    11. Console.ReadKey();
    12. }
    13. }
    14. }

    当上面的代码被编译和执行时,它会产生下列结果:

    1. #if symbol [operator symbol]...

    其中,symbol 是要测试的符号名称。您也可以使用 true 和 false,或在符号前放置否定运算符。

    常见运算符有:

    您也可以用括号把符号和运算符进行分组。条件指令用于在调试版本或编译指定配置时编译代码。一个以 #if 指令开始的条件指令,必须显示地以一个 #endif 指令终止。

    下面的程序演示了条件指令的用法:

    1. #define DEBUG
    2. #define VC_V10
    3. using System;
    4. public class TestClass
    5. {
    6. public static void Main()
    7. #if (DEBUG && !VC_V10)
    8. Console.WriteLine("DEBUG is defined");
    9. #elif (!DEBUG && VC_V10)
    10. Console.WriteLine("VC_V10 is defined");
    11. #elif (DEBUG && VC_V10)
    12. Console.WriteLine("DEBUG and VC_V10 are defined");
    13. #else
    14. Console.WriteLine("DEBUG and VC_V10 are not defined");
    15. #endif
    16. Console.ReadKey();
    17. }

    🔚