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


所有预处理指令都以 # 开头,并且每行预处理指令之前只能出现空白字符。预处理指令不是语句,因此它们不以分号 (;) 结尾。

#if

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

#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

1K+ 浏览

启动你的 职业

通过完成课程获得认证

入门
广告
© . All rights reserved.