如何在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("产生警告!");
}
}
}运行上述程序后,将生成警告,并且输出可见-
输出结果
warning CS1030: #warning: `TWO is undefined' 产生警告!