如何在 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.