我需要了解C#中#if的用法...谢谢..
#if
是一个预处理器命令。
它最常见的用法(有些人可能会说是一种滥用)是在代码中只在调试模式下编译:
#if DEBUG
Console.WriteLine("Here");
#endif
正如StingyJack所指出的那样,一种非常好的用途是允许轻松调试Windows服务:
static void Main()
{
#if (!DEBUG)
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
// Debug code: this allows the process to run as a non-service.
// It will kick off the service start point, but never kill it.
// Shut down the debugger to exit
Service1 service = new Service1();
service.<YourServicesPrimaryMethodHere>();
// Put a breakpoint on the following line to always catch
// your service when it has finished its work
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
这意味着以发布模式运行将按预期启动服务,而在调试模式下运行将允许您实际调试代码。
#if
相比其祖先 C 或 C++ 已经失去了很多优势。现在我只在以下两种情况下使用 #if
:
1)用于启用或禁用调试代码
#if DEBUG
// code inside this block will run in debug mode.
#endif
2) 使用它快速关闭代码
#if false
// all the code inside here are turned off..
#endi
#if
是编译器指令,例如你可以 #define test
然后在代码中你可以使用 #ifdef test
来编译带有 #ifdef
的代码块。