C#條件編譯

來源:互聯網
上載者:User

標籤:

條件編譯是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”);
    }
  }

C#條件編譯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.