预处理器指令向编译器提供指令,以便在实际编译开始之前对信息进行预处理。
下表列出了C#中可用的预处理器指令
Sr.No. | Preprocessor Directive & 描述 |
---|---|
1 | #define 定义一个字符序列。 链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/csharp-preprocessor-directives.html 来源:LearnFk无涯教程网 |
2 | #undef 取消定义。 |
3 | #if 允许判断,以查看它们的计算输出是否为真。 |
4 | #else 允许创建复合条件指令,以及#if。 |
5 | #elif 允许创建复合条件指令。 |
6 | #endif 指定条件指令的结束。 |
7 | #line 允许修改编译器的行号和错误/警告的文件名输出。 |
8 | #error 允许从代码中的特定位置生成错误。 |
9 | #warning 允许从代码中的特定位置生成警告。 |
10 | #region 允许您指定在使用Visual Studio代码编辑器的大纲显示功能时可以展开或折叠的代码块。 |
11 | #endRegion 标志着#Region块的结束。 |
#define预处理器指令创建符号常量。
#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指令创建条件指令,条件指令对于判断一个或多个符号以检查它们的计算输出是否为true非常有用。如果它们的计算输出为true,编译器将计算#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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)