首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

[你必須知道的 .NET] 第三十五回:判斷 DLL 為 Debug 還是 Release Build —— 反射讀取 DebuggableAttribute.IsJITTrackingEnabled

     編輯:關於.NET

如何以程式碼判斷組件是 Debug 還是 Release 建置?關鍵在於組件層級的 DebuggableAttribute:IsJITTrackingEnabled == true 表示 Debug(保留除錯資訊、追蹤 JIT),false 表示 Release(優化、無 PDB)。本文封裝泛型擴充方法 GetCustomAttribute<T>,實作 AnyContext.GetDebugMode(path),附單元測試驗證。

Debug vs Release 差異速查

特性DebugRelease
用途開發除錯部署生產
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)。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved