如何在 C# 中使用 #error 和 #warning 指令?


#error 指令

#error 指令允許從程式碼中的特定位置生成錯誤。

讓我們看一個示例 -

示例

 實際演示

using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!ONE)
         #error ONE is undefined
         #endif
         Console.WriteLine("Generating a user-defined error!");
      }
   }
}

在執行上述程式之後,會生成一個使用者自定義錯誤 -

輸出

Compilation failed: 1 error(s), 0 warnings
error CS1029: #error: 'ONE is undefined'

#warning 指令

#warning 指令允許從程式碼中的特定位置生成一級警告。

讓我們看一個示例 -

示例

 實際演示

using System;

namespace Demo {
   class Program {
      public static void Main(string[] args) {
         #if (!TWO)
         #warning TWO is undefined
         #endif
         Console.WriteLine("Generates a warning!");
      }
   }
}

在執行上述程式之後,會生成警告,並且輸出可見 -

輸出

warning CS1030: #warning: `TWO is undefined'
Generates a warning!

更新日期: 2020 年 6 月 20 日

487 次瀏覽

開啟你的 職業

透過完成課程並獲得認證

開始
廣告
© . All rights reserved.