C#條件編譯


條件編譯是C#比Java多出的東西,條件編譯在實際的項目開發中不怎么使用.但在最近的一個學習的項目中發現這類的問題,
條件編譯是C#比Java多出的東西,但我跟前輩請教后,他們都說條件編譯在實際的項目開發中不怎么使用.鑒於是新內容,我還是做做筆記,理解一下好了.
 
  條件編譯屬於編譯預處理的范疇,它能讓我們通過條件編譯的機制,將部分代碼包括進來或者排除出去,其作用與if-else類似.
 條件編譯指令有以下四種
    #if
    #elif
      #else
    #endif

 

  下面我們通一些例子來說明它們的用法
 
 
#define Debug
  class Class1
 {
      #if Debug
      void Trace(string s) {}
      #endif
 }

執行時由於第一行已經使用#define 指令定義了符號Debug, #if 的條件滿足,所以這段代碼等同於
代碼如下:

class Class1
{
   void Trace(string s) {}
}

再比如:  
代碼如下:

#define A
   #define B
   #undef C
   class D
  {
      #if C
         void F() {}
             #elif A && B
                void I() {}
      #else
         void G() {}
      #endif
  }

其編譯效果等同於:
復制代碼代碼如下:

class C
{
   void I() {}
}

#if 指令可以嵌套使用, 例如:
代碼如下:

#define Debug // Debugging on 
   #undef Trace // Tracing off
   class PurchaseTransaction
  {
      void Commit() 
    {
      #if Debug
          CheckConsistency();
          #if Trace
            WriteToLog(this.ToString());
          #endif
      #endif
      CommitHelper();
     }
  }

預編譯和條件編譯指令還可以幫助我們在程序執行過程中發出編譯的錯誤或警告,相應的指令是#warning 和#error,下面的程序展示了它們的用法:
代碼如下:

#define DEBUG 
   #define RELEASE
   #define DEMO VERSION
     #if DEMO VERSION && !DEBUG
        #warning you are building a demo version
     #endif
     #if DEBUG && DEMO VERSION
       #error you cannot build a debug demo version
     #endif
   using System;
   class Demo
  {
     public static void Main()
    {
      Console.WriteLine(“Demo application”);
    }
  }



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM