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

csharpprogrammingserver side programming更新于 2025/7/12 23:37:17

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

#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

相关文章