如何在 C# 中使用 #if..#elif…#else…#endif 指令?


所有预处理器指令以 # 开头,并且只有空白字符可以出现在行上的预处理器指令前面。预处理器指令不是语句,因此它们不会以分号 (;) 结尾。

#if

#if 指令允许测试符号或符号以查看它们是否计算为真。

#else

它允许创建复合条件指令,以及 #if。

#elif

它允许创建复合条件指令。

#endif

#endif 指示条件指令结束。

以下是一个示例,显示了 #if、#elif、#else 和 #endif 指令的使用

示例

 在线演示

#define One
#undef Two

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         #if (One && TWO)
         Console.WriteLine("Both are defined");
         #elif (ONE && !TWO)
         Console.WriteLine("ONE is defined and TWO is undefined");
         #elif (!ONE && TWO)
         Console.WriteLine("ONE is defined and TWO is undefined");
         #else
         Console.WriteLine("Both are undefined");
         #endif
      }
   }
}

输出

Both are undefined

更新于: 20-Jun-2020

1 千次 + 浏览

开启你的 职业生涯

通过完成课程获得认证。

立即开始
广告
© . All rights reserved.