[英]What is the use of #if in C#?
我需要知道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.<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
}
這意味着運行釋放模式將按預期啟動服務,而在調試模式下運行將允許您實際調試代碼。
“當C#編譯器遇到#if指令,最后是#endif指令時,只有在定義了指定的符號時,它才會在指令之間編譯代碼”
這是MSDN鏈接。
#if(C#Reference)是一個編譯器指令。 有關詳細信息,請參閱MSDN文章。
#if
是一個編譯器指令,例如你可以#define test
稍后在代碼中,您可以使用#ifdef
測試#ifdef test
compile code block
與其祖先相比, #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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.