在解決方案屬性中,我將Configuration設置爲「release」,用於我惟一的項目。 測試
在主程序的開頭,我有這個代碼,它顯示「Mode = Debug」。 我也在最頂端有這兩行: spa
#define DEBUG #define RELEASE
我在測試正確的變量嗎? debug
#if (DEBUG) Console.WriteLine("Mode=Debug"); #elif (RELEASE) Console.WriteLine("Mode=Release"); #endif
個人目標是根據調試版本和發佈模式爲變量設置不一樣的默認值。 調試
命名空間 code
using System.Resources; using System.Diagnostics;
方法 進程
private static bool IsDebug() { object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false); if ((customAttributes != null) && (customAttributes.Length == 1)) { DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute; return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled); } return false; }
我不是#if的忠實粉絲,特別是若是你把它所有傳播到你的代碼庫中,由於它會給你調試構建經過的問題,但若是你不當心,Release版本會失敗。 get
因此這就是個人想法(靈感來自C#中的#ifdef ): 編譯器
public interface IDebuggingService { bool RunningInDebugMode(); } public class DebuggingService : IDebuggingService { private bool debugging; public bool RunningInDebugMode() { //#if DEBUG //return true; //#else //return false; //#endif WellAreWe(); return debugging; } [Conditional("DEBUG")] private void WellAreWe() { debugging = true; } }
因爲這些COMPILER指令的目的是告訴編譯器不要包含代碼,調試代碼,beta代碼或者全部最終用戶所需的代碼,除了那些廣告部門,即你想要的#Define AdDept可以根據您的須要包含或刪除它們。 若是非AdDept合併到AdDept中,則無需更改源代碼。 而後,全部須要作的就是在程序的現有版本的編譯器選項屬性頁面中包含#AdDept指令並進行編譯並執行! 合併後的程序代碼會活躍起來! it
您可能還但願對新進程使用聲明,該進程還沒有準備好進入黃金時段,或者在發佈代碼以前沒法在代碼中處於活動狀態。 io
不管如何,這就是我這樣作的方式。
若是您嘗試使用爲構建類型定義的變量,則應刪除這兩行...
#define DEBUG #define RELEASE
...這些將致使#if(DEBUG)始終爲真。
RELEASE也沒有默認的條件編譯符號。 若是要定義一個轉到項目屬性,請單擊「 生成」選項卡,而後將「RELEASE」添加到「 常規」標題下的「 條件編譯符號」文本框中。
另外一種選擇是這樣作......
#if DEBUG Console.WriteLine("Debug"); #else Console.WriteLine("Release"); #endif
默認狀況下,若是項目在調試模式下編譯,則Visual Studio定義DEBUG,若是項目處於發佈模式,則不定義DEBUG。 默認狀況下,RELEASE未在發佈模式中定義。 使用這樣的東西:
#if DEBUG // debug stuff goes here #else // release stuff goes here #endif
若是您只想在發佈模式下執行某些操做:
#if !DEBUG // release... #endif
此外,值得指出的是,您能夠對返回void
方法使用[Conditional("DEBUG")]
屬性,只有在定義了某個符號時才執行它們。 若是未定義符號,編譯器將刪除對這些方法的全部調用:
[Conditional("DEBUG")] void PrintLog() { Console.WriteLine("Debug info"); } void Test() { PrintLog(); }