闽公网安备 35020302035485号
网友A
这种多条件的解决方案太多了,这边列几种可供参考。
static void Main(string[] args)
{
[Conditional("DEBUG")]
static void Method() { }
Method();
}
2. #if 预处理指令#if DEBUG
static int testCounter = 0;
#endif
需要提醒一下,这个预处理指令不像 C, C++ 那种可以带逻辑条件, C# 中的if预处理指令只能是一种 boolean 型表达式。Debug.Write("Something to write in Output window.");
最后稍微提醒一下,使用 #if 预处理指令时在特定环境下对变量的赋值一定要记得多测试,比如下面的场景。 string sth = null;
#if DEBUG
sth = "oh, hi!";
#endif
Console.WriteLine(sth);
如果当前是 Debug 环境,那么 str = oh, hi,如果为 Release 环境,那么 str=null,在某些情况下可能会造成 NullReferenceException 异常。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;
}
}
只需要判断是否被调试器附加了就可以执行特定代码,完美。