如何基于发布或调试构建模式运行一些代码?

问题描述

我有一个变量(即 bool releaseMode = false;) 我希望根据我们是否处于发布模式(releaseMode = true;)其他调试模式(releaseMode = false;

来设置变量的值

解决方法

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

/// <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")