在解决方案属性中,我已经将我唯一的项目的配置设置为“发布”。

在主例程的开头,我有这样的代码,它显示“Mode=Debug”。 我在最上面还有这两行:

#define DEBUG 
#define RELEASE

我测试的变量对吗?

#if (DEBUG)
            Console.WriteLine("Mode=Debug"); 
#elif (RELEASE)
            Console.WriteLine("Mode=Release"); 
#endif

我的目标是根据调试和发布模式为变量设置不同的默认值。


当前回答

默认情况下,如果项目在调试模式下编译,Visual Studio定义DEBUG,如果项目在发布模式下编译,则不定义DEBUG。默认情况下,RELEASE模式中没有定义RELEASE。可以这样说:

#if DEBUG
  // debug stuff goes here
#else
  // release stuff goes here
#endif

如果你只想在发布模式下做某事:

#if !DEBUG
  // release...
#endif

此外,值得指出的是,您可以在返回void的方法上使用[Conditional("DEBUG")]属性,以便仅在定义了某个符号时执行它们。如果符号没有定义,编译器将删除对这些方法的所有调用:

[Conditional("DEBUG")]
void PrintLog() {
    Console.WriteLine("Debug info");
}

void Test() {
    PrintLog();
}

其他回答

It is worth noting here that one of the most significant differences between conditionally executing code based on #if DEBUG versus if(System.Diagnostics.Debugger.IsAttached) is that the compiler directive changes the code that is compiled. That is, if you have two different statements in an #if DEBUG/#else/#endif conditional block, only one of them will appear in the compiled code. This is an important distinction because it allows you do do things such as conditionally compile method definitions to be public void mymethod() versus internal void mymethod() depending on build type so that you can, for example, run unit tests on debug builds that will not break access control on production builds, or conditionally compile helper functions in debug builds that will not appear in the final code if they would violate security in some way should they escape into the wild. The IsAttached property, on the other hand, does not affect the compiled code. Both sets of code are in all of the builds - the IsAttached condition will only affect what is executed. This by itself can present a security issue.

默认情况下,如果项目在调试模式下编译,Visual Studio定义DEBUG,如果项目在发布模式下编译,则不定义DEBUG。默认情况下,RELEASE模式中没有定义RELEASE。可以这样说:

#if DEBUG
  // debug stuff goes here
#else
  // release stuff goes here
#endif

如果你只想在发布模式下做某事:

#if !DEBUG
  // release...
#endif

此外,值得指出的是,您可以在返回void的方法上使用[Conditional("DEBUG")]属性,以便仅在定义了某个符号时执行它们。如果符号没有定义,编译器将删除对这些方法的所有调用:

[Conditional("DEBUG")]
void PrintLog() {
    Console.WriteLine("Debug info");
}

void Test() {
    PrintLog();
}

删除顶部的定义

#if DEBUG
        Console.WriteLine("Mode=Debug"); 
#else
        Console.WriteLine("Mode=Release"); 
#endif

对Tod Thomson的答案稍加修改(私生子化?),将其作为一个静态函数而不是一个单独的类(我希望能够从我已经包含的viewutils类中调用它)。

public static bool isDebugging() {
    bool debugging = false;

    WellAreWe(ref debugging);

    return debugging;
}

[Conditional("DEBUG")]
private static void WellAreWe(ref bool debugging)
{
    debugging = true;
}

我更喜欢这样检查它,而不是寻找#define指令:

if (System.Diagnostics.Debugger.IsAttached)
{
   //...
}
else
{
   //...
}

需要注意的是,您当然可以在调试模式下编译和部署一些东西,但仍然没有附加调试器。