如何使用 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.