以编程方式检测发布/调试模式(.NET)

rip*_*234 60 .net debugging release

可能重复:
如何确定是否使用TRACE或DEBUG标志编译.NET程序集

可能重复:
如何识别DLL是否为Debug或Release版本(在.NET中)

以编程方式检查当前程序集是在Debug或Release模式下编译的最简单方法是什么?

Dav*_*man 119

bool isDebugMode = false;
#if DEBUG
isDebugMode = true;
#endif
Run Code Online (Sandbox Code Playgroud)

如果要在调试版本和发布版本之间编写不同的行为,您应该这样做:

#if DEBUG
   int[] data = new int[] {1, 2, 3, 4};
#else
   int[] data = GetInputData();
#endif
   int sum = data[0];
   for (int i= 1; i < data.Length; i++)
   {
     sum += data[i];
   }
Run Code Online (Sandbox Code Playgroud)

或者如果你想对函数的调试版本进行某些检查,你可以这样做:

public int Sum(int[] data)
{
   Debug.Assert(data.Length > 0);
   int sum = data[0];
   for (int i= 1; i < data.Length; i++)
   {
     sum += data[i];
   }
   return sum;
}
Run Code Online (Sandbox Code Playgroud)

Debug.Assert将不包含在发布版本中.


Jho*_*re- 13

我希望这对你有用:

public static bool IsRelease(Assembly assembly) {
    object[] attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), true);
    if (attributes == null || attributes.Length == 0)
        return true;

    var d = (DebuggableAttribute)attributes[0];
    if ((d.DebuggingFlags & DebuggableAttribute.DebuggingModes.Default) == DebuggableAttribute.DebuggingModes.None)
        return true;

    return false;
}

public static bool IsDebug(Assembly assembly) {
    object[] attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), true);
    if (attributes == null || attributes.Length == 0)
        return true;

    var d = (DebuggableAttribute)attributes[0];
    if (d.IsJITTrackingEnabled) return true;
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么两个函数都有这一行:if(attributes == null || attributes.Length == 0)return true; 这段代码有问题.我确实给它+1了,因为答案提供了一种真正的编程方式,而不是用于获得旗帜的同步方式.有时需要知道调试模式中是否将其表示为代码本身的一部分而不是编译器标志. (4认同)
  • 在一般情况下,我将@DaveB推迟到这个问题上.但是,你的问题很广泛,如果你只是想让你的代码在测试时表现不同,我发现这个测试很有用(在VB.Net中)`如果System.Diagnostics.Debugger.IsAttached那么DoSomething'(如表格表现不同)` (4认同)
  • 如果在“发布”模式下进行编译并将DebugOutput选择为“ none”以外的任何内容,则将出现DebuggableAttribute。因此,此答案不正确。它甚至不寻找JIT Optimization标志。请参阅我的文章,了解如何手动和以编程方式区分两者-http://dave-black.blogspot.com/2011/12/how-to-tell-if-assembly-is-debug-or.html (2认同)