我需要知道C#中#if的用法......谢谢..
答案 0 :(得分:23)
最常见的用法(有人可能会说是滥用)是让代码只能在调试模式下编译:
#if DEBUG
Console.WriteLine("Here");
#endif
一个非常好的用法(如StingyJack points out)允许轻松调试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.<Your Service's Primary Method Here>();
// 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
}
这意味着正在运行的发布模式将按预期启动服务,而在调试模式下运行将允许您实际调试代码。
答案 1 :(得分:4)
“当C#编译器遇到#if指令,最后是#endif指令时,只有在定义了指定的符号时才会编译指令之间的代码”
以下是MSDN链接。
答案 2 :(得分:2)
#if (C# Reference)是编译器指令。有关详细信息,请参阅MSDN文章。
答案 3 :(得分:0)
它用于预处理程序指令,请参阅此处http://msdn.microsoft.com/en-us/library/4y6tbswk(v=VS.71).aspx
答案 4 :(得分:0)
#if
是一个编译器指令,例如你可以#define test
以及稍后在代码中您可以测试#ifdef test
使用#ifdef
答案 5 :(得分:0)
#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