C#中的預先處理指令,你用了多少?

來源:互聯網
上載者:User

C#中的預先處理指令

作為預先處理中的一對:#region name ,#endregion可能是大家使用得最多的,我也常用它來進行代碼分塊,在一個比較長的cs檔案中,這麼做確實是一件可以讓你使代碼更清晰的好辦法,VS也自動用這個來包含自動產生的程式碼,它這麼做既可以使開發人員更清晰的查看自己的代碼,也開了一個好頭,使更多人使用#region。

C#中還有好幾對預先處理指令,可能大家就用得比較少了。

#define symbol

#undef symbol

#if symbol [operator symbol2]...

#else

#elif symbol [operator symbol2]

#endif

#warning text text指在編譯器輸出中的警告文字

#error text  text指在編譯器輸出中的錯誤資訊

#line number

關於#define要說明幾點,#define DEBUG 等效於不寫這句話,你要不定義它才一定要寫上#undefin DEBUG

 (C# Essentials一書中說 #define DEBUG 等效於#define DEBUG true,不過這個好像有問題)

這一段代碼可以說明好幾個命令:

#define DEBUG

#define VC_V6

using System;

public class MyClass

{

   public static void Main()

   {

      #if (DEBUG && !VC_V6)

         Console.WriteLine("DEBUG is defined");

      #elif (!DEBUG && VC_V6)

         Console.WriteLine("VC_V6 is defined");

      #elif (DEBUG && VC_V6)

         Console.WriteLine("DEBUG and VC_V6 are defined");

      #else

         Console.WriteLine("DEBUG and VC_V6 are not defined");

      #endif

   }

}

我們可以用這些指令來自動處理測試期和發布期資料庫的連接字串之類的工作

#if !RELEASE

constr = testSQLServerConnectionString

#else

constr = releaseSQLServerConnectionString

#endif

在編代碼時加上一句#undef RESEASE,發布後刪除這一句就行了。


#define DEBUG

using System;

namespace SyntaxTest

{

 public class Class2

 {

  public Class2()

  {

   #if DEBUG

          #warning DEBUG is defined

      #endif

  }

 }

}

以上代碼會在編譯時間產生一個警告。


#define DEBUG

using System;

namespace SyntaxTest

{

 public class Class2

 {

  public Class2()

  {

   #if DEBUG

          #error DEBUG is defined

      #endif

  }

 }

}

以上代碼會在編譯時間產生一個錯誤,編譯不通過,所以我們可以利用以上兩種指令進行一些自訂的編譯檢測。

#line 使您得以修改編譯器的行號以及(可選)錯誤和警告的檔案名稱輸出。

#line [ number ["file_name"] | default ]

number

要為原始碼檔案中後面的行指定的編號。

"file_name"(可選)

希望出現在編譯器輸出中的檔案名稱。預設情況下,使用原始碼檔案的實際名稱。檔案名稱必須括在雙引號 ("") 中。

default

重設檔案中的行編號。

備忘

#line 可能由產生過程中的自動中間步驟使用。例如,如果中間步驟從原始的原始碼檔案中移除行,但是您仍希望編譯器基於檔案中的原始行號產生輸出,則可以移除行,然後用 #line 類比原始行號。


public class MyClass2

{

   public static void Main()

   {

      #line 200

      int i;   // 這一行在200行,不過在VS中看到的還是6

      #line default

      char c;   // 這一行在7行,不過在VS中看到的還是8

   }

}

 

警請批評指正。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.