C# 预处理器指令
预处理器指令(Preprocessor Directives)指导编译器在实际编译开始之前对信息进行预处理。
通过这些指令,可以控制编译器如何编译文件或编译哪些部分。常见的预处理器指令包括条件编译、宏定义等。
所有的预处理器指令都是以 # 开始,且在一行上,只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句,所以它们不以分号 ; 结束。
C# 编译器没有一个单独的预处理器,但是,指令被处理时就像是有一个单独的预处理器一样。在 C# 中,预处理器指令用于在条件编译中起作用。与 C 和 C++ 不同的是,它们不是用来创建宏。一个预处理器指令必须是该行上的唯一指令。
C# 预处理器指令列表
下表列出了 C# 中可用的预处理器指令:
| 指令 | 描述 |
|---|---|
#define |
定义一个符号,可以用于条件编译。 |
#undef |
取消定义一个符号。 |
#if |
开始一个条件编译块,如果符号被定义则包含代码块。 |
#elif |
如果前面的 #if 或 #elif 条件不满足,且当前条件满足,则包含代码块。 |
#else |
如果前面的 #if 或 #elif 条件不满足,则包含代码块。 |
#endif |
结束一个条件编译块。 |
#warning |
生成编译器警告信息。 |
#error |
生成编译器错误信息。 |
#region |
标记一段代码区域,可以在IDE中折叠和展开这段代码,便于代码的组织和阅读。 |
#endregion |
结束一个代码区域。 |
#line |
更改编译器输出中的行号和文件名,可以用于调试或生成工具的代码。 |
#pragma |
用于给编译器发送特殊指令,例如禁用或恢复特定的警告。 |
#nullable |
控制可空性上下文和注释,允许启用或禁用对可空引用类型的编译器检查。 |
实例
#define DEBUG
#if DEBUG
Console.WriteLine("Debug mode");
#elif RELEASE
Console.WriteLine("Release mode");
#else
Console.WriteLine("Other mode");
#endif
#warning This is a warning message
#error This is an error message
#region MyRegion
// Your code here
#endregion
#line 100 "MyFile.cs"
// The next line will be reported as line 100 in MyFile.cs
Console.WriteLine("This is line 100");
#line default
// Line numbering returns to normal
#pragma warning disable 414
private int unusedVariable;
#pragma warning restore 414
#nullable enable
string? nullableString = null;
#nullable disable
define 和 #undef 预处理器
#define 用于定义符号(通常用于条件编译),#undef 用于取消定义符号。
#define DEBUG
#undef RELEASE
#define 允许您定义一个符号,这样,通过使用符号作为传递给 #if 指令的表达式,表达式将返回 true。它的语法如下:
#define symbol
下面的程序说明了这点:
实例
#define PI
using System;
namespace PreprocessorDAppl
{
class Program
{
static void Main(string[] args)
{
#if (PI)
Console.WriteLine("PI is defined");
#else
Console.WriteLine("PI is not defined");
#endif
Console.ReadKey();
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:
PI is defined
条件指令:#if, #elif, #else 和 #endif
您可以使用 #if 指令来创建一个条件指令。
条件指令用于测试符号是否为真。如果为真,编译器会执行 #if 和下一个指令之间的代码。
条件指令的语法:
#if symbol [operator symbol]...
其中,symbol 是要测试的符号名称。您也可以使用 true 和 false,或在符号前放置否定运算符。
常见运算符有:
- == (等于)
- != (不等于)
- && (与)
- || (或)
您也可以用括号把符号和运算符进行分组。




评论一下吧
取消回复