C# preprocessor directives
Preprocessor directives direct the compiler to preprocess information before actual compilation begins.
All preprocessor directives start with #. And on a line, only whitespace characters can appear before preprocessor directives. Preprocessor directives are not statements, so they do not end with a semicolon (;).
The C# compiler does not have a separate preprocessor, however, directives are processed as if there were a separate preprocessor. In C#, preprocessor directives are used to function in conditional compilation. Unlike C and C++, they are not used to create macros. A preprocessor directive must be the only directive on the line.
List of C# Preprocessor Directives
The following table lists the preprocessor directives available in C#:
预处理器指令 | 描述 |
---|---|
#define | 它用于定义一系列成为符号的字符。 |
#undef | 它用于取消定义符号。 |
#if | 它用于测试符号是否为真。 |
#else | 它用于创建复合条件指令,与 #if 一起使用。 |
#elif | 它用于创建复合条件指令。 |
#endif | 指定一个条件指令的结束。 |
#line | 它可以让您修改编译器的行数以及(可选地)输出错误和警告的文件名。 |
#error | 它允许从代码的指定位置生成一个错误。 |
#warning | 它允许从代码的指定位置生成一级警告。 |
#region | 它可以让您在使用 Visual Studio Code Editor 的大纲特性时,指定一个可展开或折叠的代码块。 |
#endregion | 它标识着 #region 块的结束。 |
#define Preprocessor
The #define preprocessor directive creates symbolic constants.
#define allows you to define a symbol such that, by using the symbol as an expression passed to the #if directive, the expression will return true. Its syntax is as follows:
- #define symbol
The following program illustrates this:
- #define PI
- using System;
- namespace PreprocessorDAppl
- {
- class Program
- {
- staticvoid Main(string[] args)
- {
- #if (PI)
- Console.WriteLine("PI is defined");
- #else
- Console.WriteLine("PI is not defined");
- #endif
- Console.ReadKey();
- }
- }
- }
当上面的代码被编译和执行时,它会产生下列结果:
- PI is defined
条件指令
您可以使用 #if 指令来创建一个条件指令。条件指令用于测试符号是否为真。如果为真,编译器会执行 #if 和下一个指令之间的代码。
条件指令的语法:
- #if symbol [operator symbol]...
其中,symbol 是要测试的符号名称。您也可以使用 true 和 false,或在符号前放置否定运算符。
常见运算符有:
- == (等于)
- != (不等于)
- && (与)
- || (或)
您也可以用括号把符号和运算符进行分组。条件指令用于在调试版本或编译指定配置时编译代码。一个以 #if 指令开始的条件指令,必须显示地以一个 #endif 指令终止。
下面的程序演示了条件指令的用法:
- #define DEBUG
- #define VC_V10
- using System;
- public class TestClass
- {
- public static void Main()
- {
- #if (DEBUG && !VC_V10)
- Console.WriteLine("DEBUG is defined");
- #elif (!DEBUG && VC_V10)
- Console.WriteLine("VC_V10 is defined");
- #elif (DEBUG && VC_V10)
- Console.WriteLine("DEBUG and VC_V10 are defined");
- #else
- Console.WriteLine("DEBUG and VC_V10 are not defined");
- #endif
- Console.ReadKey();
- }
- }
当上面的代码被编译和执行时,它会产生下列结果:
- DEBUG and VC_V10 are defined