【问题标题】:How to run some code based on release or debug build mode?如何根据发布或调试构建模式运行一些代码?
【发布时间】:2021-06-04 08:28:05
【问题描述】:

我有一个变量(即bool releaseMode = false;) 我希望根据我们是否处于发布模式(releaseMode = true;)或者调试模式(releaseMode = false;)来设置变量的值

【问题讨论】:

    标签: c# conditional-compilation release-mode debug-mode conditional-execution


    【解决方案1】:

    根据您的问题,您可以使用:

    /// <summary>
    /// Indicate if the executable has been generated in debug mode.
    /// </summary>
    static public bool IsDebugExecutable
    {
      get
      {
        bool isDebug = false;
        CheckDebugExecutable(ref isDebug);
        return isDebug;
      }
    }
    
    [Conditional("DEBUG")]
    static private void CheckDebugExecutable(ref bool isDebug)
      => isDebug = true;
    

    当然你可以把名字换成:

    IsReleaseExecutable
    
    return !isDebug;
    

    这种方法意味着所有代码都被编译。因此,任何代码都可以根据这个标志以及与用户或程序有关的任何其他行为参数来执行,例如调试和跟踪引擎的激活或停用。例如:

    if ( IsDebugExecutable || UserWantDebug )  DoThat();
    

    其他预处理指令如下:

    C# if/then directives for debug vs release

    #if DEBUG vs. Conditional("DEBUG")

    【讨论】:

    • 这段代码怎么样:#if DEBUG releaseMode = false; #else releaseMode = true; #endif
    • 如你所愿。选择最适合您、最适合您和环境的方法。选择您认为最清晰、最干净、最高效和最可维护的内容。在阅读和测试了几件事后,我个人选择了我认为最整洁的建议代码。
    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多