C#中的#if有什么用途?

15

我需要了解C#中#if的用法...谢谢..

6个回答

30

#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 
}

Source

这意味着以发布模式运行将按预期启动服务,而在调试模式下运行将允许您实际调试代码。


1
我见过的最好的#if使用... http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx - StingyJack

4

#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

4
当C#编译器遇到#if指令,最终跟着一个#endif指令时,只有在定义了指定的符号时,它才会编译指令之间的代码。
这是MSDN链接。

2

#if (C# 参考) 是一个编译器指令。请参阅 MSDN 文章以获取更多信息。


0

0

#if 是编译器指令,例如你可以 #define test

然后在代码中你可以使用 #ifdef test 来编译带有 #ifdef 的代码块。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接