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

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

#define DEBUG 
#define RELEASE

我测试的变量对吗?

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

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


当前回答

如果您试图使用为构建类型定义的变量,您应该删除这两行…

#define DEBUG  
#define RELEASE 

... 这将导致#if (DEBUG)始终为真。

RELEASE也没有默认的条件编译符号。如果您想定义一个转到项目属性,单击Build选项卡,然后将RELEASE添加到General标题下的Conditional编译符号文本框中。

另一个选择是这样做……

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

其他回答

我得想个更好的办法。我明白了,#if块是其他配置中的有效注释(假设DEBUG或RELEASE;但任何符号都适用)

public class Mytest
    {
        public DateTime DateAndTimeOfTransaction;
    }

    public void ProcessCommand(Mytest Command)
        {
            CheckMyCommandPreconditions(Command);
            // do more stuff with Command...
        }

        [Conditional("DEBUG")]
        private static void CheckMyCommandPreconditions(Mytest Command)
        {
            if (Command.DateAndTimeOfTransaction > DateTime.Now)
                throw new InvalidOperationException("DateTime expected to be in the past");
        }

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

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

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

删除顶部的定义

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

删除定义并检查条件是否处于调试模式。你不需要检查指令是否处于释放模式。

就像这样:

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

名称空间

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;
    }