如何以程式碼判斷組件是 Debug 還是 Release 建置?關鍵在於組件層級的 DebuggableAttribute:IsJITTrackingEnabled == true 表示 Debug(保留除錯資訊、追蹤 JIT),false 表示 Release(優化、無 PDB)。本文封裝泛型擴充方法 GetCustomAttribute<T>,實作 AnyContext.GetDebugMode(path),附單元測試驗證。
| 特性 | Debug | Release |
|---|---|---|
| 用途 | 開發除錯 | 部署生產 |
| PDB 檔 | 產生 | 不產生 |
| Debug.WriteLine | 輸出 | 忽略 |
| Trace.WriteLine | 輸出 | 輸出 |
| #define DEBUG | 預設定義 | 未定義 |
| 程式碼優化 | 關閉 | 開啟 |
public static class Utils
{
public static T GetCustomAttribute<T>(this ICustomAttributeProvider provider)
where T : Attribute
{
var attrs = provider.GetCustomAttributes(typeof(T), false);
return attrs.Length > 0 ? attrs[0] as T : default(T);
}
}
public enum DebugMode { Debug, Release }
public class AnyContext
{
public static DebugMode GetDebugMode(string assemblyPath)
{
if (string.IsNullOrEmpty(assemblyPath))
throw new ArgumentNullException(nameof(assemblyPath));
var asm = Assembly.LoadFile(assemblyPath);
var attr = asm.GetCustomAttribute<DebuggableAttribute>();
return attr.IsJITTrackingEnabled ? DebugMode.Debug : DebugMode.Release;
}
}
[TestMethod]
public void TestIsDebugOrRelease()
{
string debugAsm = @"D:\debugass.exe";
string releaseAsm = @"D:\releaseass.exe";
Assert.AreEqual("Debug", AnyContext.GetDebugMode(debugAsm).ToString());
Assert.AreEqual("Release", AnyContext.GetDebugMode(releaseAsm).ToString());
}
適用 .NET 2.0+,若組件無 DebuggableAttribute 將回傳 Release(default(DebuggableAttribute) 為 null,IsJITTrackingEnabled 為 false)。