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

C# 如何基于发布或调试构建模式运行某些代码?,c#,conditional-compilation,release-mode,debug-mode,conditional-execution,C#,Conditional Compilation,Release Mode,Debug Mode,Conditional Execution,我有一个变量(即bool releaseMode=false;) 我希望根据我们是否处于释放模式(releaseMode=true;)或调试模式(releaseMode=false;)设置变量的值。在您的问题中,您可以使用: /// <summary> /// Indicate if the executable has been generated in debug mode. /// </summary> static public bool IsDebugExecu

我有一个变量(即
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;
这种方法意味着所有代码都是编译的。因此,可以根据该标志以及与用户或程序有关的任何其他行为参数来执行任何代码,例如调试和跟踪引擎的激活或停用。例如:

if ( IsDebugExecutable || UserWantDebug )  DoThat();
否则,可以使用如下预处理器指令:


这段代码如何:#如果DEBUG releaseMode=false#else releaseMode=true#只要你愿意。选择最适合您的方法,这是最适合您和上下文的方法。选择您认为最清晰、最干净、最高效和最可维护的内容。就我个人而言,在阅读和测试了一些东西之后,我选择了建议的代码,我发现这是最整洁的。
if ( IsDebugExecutable || UserWantDebug )  DoThat();