在C#中,有兩種進(jìn)行條件編譯的方法:
。預(yù)處理用法
。條件屬性
#define DEBUG
這樣定義了符號(hào)DEBUG,且范圍在它所定義的文件內(nèi)。請(qǐng)注意,必須要先定義符號(hào)才能使用其它語(yǔ)句。例如,以下代碼段是不正確的:
using System;
#define DEBUG
你也可以使用編譯器定義符號(hào)(用于所有的文件):
csc /define:DEBUG mysymbols.cs
如果你想用編譯器定義多種符號(hào),只需用分號(hào)隔開(kāi)它們:
csc /define:RELEASE;DEMOVERSION mysymbols.cs
在C#源文件中,對(duì)這兩種符號(hào)的定義分為兩行 #define 標(biāo)志。
你也可以使用邏輯“與”(&&)、邏輯“或”(||)以及“否”(!)
#define DEBUG
#define RELEASE
#define DEMOVERSION
#if DEMOVERSION && !DEBUG
#warning You are building a demo version
#endif
#if DEBUG && DEMOVERSION
#error You cannot build a debug demo version
#endif
//在解決方案的屬性-生成中,也有相關(guān)的條件編譯符號(hào)定義
//所以不能直接注釋掉DEBUG,定義REALEASE
#define DEBUG
/*
#if DEBUG
#undef DEBUG
#endif
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace ConditionalCombilation
{
class Program
{
static void
{
#if DEBUG
Console.WriteLine("DEBUG");
#elif RELEASE
Console.WriteLine("RELEASE");
#endif
OutTime(15);
Console.ReadLine();
}
[Conditional("DEBUG")]
private static void OutTime(int timetake)
{
Console.WriteLine(timetake.ToString() + "ms used");
}
}
}
聯(lián)系客服