在C#下,如何让一段代码只执行在DEBUG模式下

Conditional 特性

这个特性会告诉编译器除非遇到指定的编译符号,否则将会被忽略,参考下面的例子:

static void Main(string[] args)
{
    [Conditional("DEBUG")]
    static void Method() { }
 
    Method();
}

预处理指令

当你用了 #if … #end if 成对预处理指定时,当遇到编译符号与定义的环境一致时将会执行此if。

#if DEBUG
    static int testCounter = 0;
#endif

需要提醒一下,这个预处理指令不像 C, C++ 那种可以带逻辑条件, C# 中的if预处理指令只能是一种 boolean 型表达式。

Diagnostics下的IsAttached属性

if (System.Diagnostics.Debugger.IsAttached)
{
    // Code here
}

属性解释如下:

//
// Summary:
//     Gets a value that indicates whether a debugger is attached to the process.
//
// Returns:
//     true if a debugger is attached; otherwise, false.
public static bool IsAttached
{
    get
    {
        throw null;
    }
}