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
}
}
警請批評指正。