簡體   English   中英

從 .NET 庫中,如何檢查 RUNNING 程序集/應用程序是否處於調試版本(未附加調試器)?

[英]From a .NET library, how to check if the RUNNING assembly/app is in Debug build (without Debugger attached)?

我正在制作一個 class 庫Foo (Xamarin Android 庫,如果相關,但我更喜歡通用的 .NET 解決方案,如果可能的話),我需要這樣的東西:

if (builtInDebugConfig) 
{
    this.DoSomething();
}

現在Foo.dll肯定會在調用上述代碼時以 Release 模式編譯。 因此#if肯定是不可能的, Conditional也不應該工作(如果我錯了,請糾正我,我也讀過它是一個編譯器屬性) (問題的答案和我的測試確認Conditional有效)。 我能想到的最接近的是Debugger.IsAttached ,但是大多數時候我們在沒有附加調試器的情況下測試應用程序。

有沒有辦法檢測調用程序集是否使用DEBUG符號/配置編譯? 如果可能的話,我不希望調用(應用程序)代碼在每個應用程序中都有這樣的東西,因為它違背了目的:

#if DEBUG
    Foo.IsDebug = true;
#endif

更新:澄清我為什么要這樣做:如果調用應用程序正在開發中並且不希望此類代碼存在於最終視圖中,我想啟用調試代碼(即啟用 WebView 調試信號)。 這就是為什么我對防止此類代碼泄漏到 Release 構建的解決方案感興趣的原因。

您可以在Foo中使用Conditional來裝飾方法 - 對該方法的任何調用都取決於調用代碼是否定義了相關符號。 所以像:

[Conditional("DEBUG")]
public void MaybeSetDebugMode()
{
    // Remember the decision
}

那么調用代碼就可以無條件地編寫調用MaybeSetDebugMode的代碼,並且只有在編譯調用代碼時定義了DEBUG時才會真正編譯調用。 Foo本身中的方法將被編譯為Foo.dll ,而不管編譯時定義的符號。

這與#if不同,后者在編譯代碼時確實取決於符號。

請注意,這就是Debug.WriteLine等的工作方式。

這樣做的一個缺點:除非您采取更多行動,否則此代碼絕對會存在於“最終構建”中。 它必須,因為 Foo.dll 中存在的代碼不能根據調用它的內容而改變。

因此,您實際上可能想改用#if ,例如:

#if FINAL_BUILD
public void MaybeSetDebugMode()
{
    // This method exists so that the calling code will still build
    // with the final DLL, but there won't be any "interesting" code
    // for anyone to find.
}

#else

public void MaybeSetDebugMode()
{
    // Interesting code goes here. This code won't be included in the final build,
    // but callers can call it unconditionally, because there'll be an empty
    // method in the final build.
}
#endif

感謝評論和答案,我找到了兩個可行的解決方案,兩者都很棒,但我想我會在我的最終項目中使用Conditional IsExecutingDebug檢查DebuggableAttribute是否存在於 Entry 程序集中,而Jon Skeet 的回答中解釋了Conditional

namespace ClassLibrary1
{
    public class Class1
    {

        public bool IsExecutingDebug()
        {
#if DEBUG
            Console.WriteLine("Debug in lib");
#endif

            return Assembly.GetExecutingAssembly().IsInDebug();
        }

        [Conditional("DEBUG")]
        public void ExecuteInDebugOnly()
        {
            Console.WriteLine("Hi!");
        }

    }
}

namespace System
{

    public static class MyExtensions
    {
        public static bool IsInDebug(this Assembly assembly)
        {
            return assembly.GetCustomAttributes<DebuggableAttribute>().Any();
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM