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

在主例程的开头,我有这样的代码,它显示“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();
}

其他回答

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

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

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

确保在“项目生成属性”中定义了DEBUG常量。这将启用#if DEBUG。我没有看到预定义的RELEASE常量,所以这可能意味着任何不在DEBUG块中的东西都是RELEASE模式。

一个可以为您节省大量时间的技巧-不要忘记,即使您在构建配置下选择了调试(在vs2012/13菜单中,它在build => configuration MANAGER下)-这是不够的。

你需要注意PUBLISH配置,比如:

名称空间

using System.Resources;
using System.Diagnostics;

方法

   private static bool IsDebug()
    {
        object[] customAttributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(DebuggableAttribute), false);
        if ((customAttributes != null) && (customAttributes.Length == 1))
        {
            DebuggableAttribute attribute = customAttributes[0] as DebuggableAttribute;
            return (attribute.IsJITOptimizerDisabled && attribute.IsJITTrackingEnabled);
        }
        return false;
    }

DEBUG/_DEBUG应该已经在VS中定义了。

在代码中删除#define DEBUG。在构建配置中为特定的构建设置预处理器。

它打印“Mode=Debug”的原因是因为你的#define,然后跳过elif。

正确的检查方法是:

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

不要检查RELEASE。