以编程方式检测Release/Debug模式(.NET)

68
2个回答

146
bool isDebugMode = false;
#if DEBUG
isDebugMode = true;
#endif

如果你想在调试版和发布版之间编写不同的代码行为,应该按照以下方式进行:

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

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

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

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


OP是在询问JIT优化构建吗?如果是,那么这个答案是不正确的。Debug属性可以在JIT优化构建或非优化构建中声明。 - Dave Black

15

我希望这对你有用:

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

4
为什么两个函数都有这行代码: if (attributes == null || attributes.Length == 0) return true; 这段代码有问题。 我点赞了这个答案,因为它提供了一种真正的编程方法来获取标志,而不是基于语法的方法。有时需要知道是否处于调试模式,这要作为代码本身的一部分来表达,而不是作为编译器标志。 - G.Y
2
如果您在发布模式下编译并选择DebugOutput为除“none”以外的任何选项,则会出现DebuggableAttribute。因此,这个答案是不正确的。它甚至没有查找JIT优化标志。请参考我的帖子,了解如何手动和程序化地区分两者的差异-http://dave-black.blogspot.com/2011/12/how-to-tell-if-assembly-is-debug-or.html - Dave Black
5
我在一般情况下会听从@DaveB的意见,关于这个问题的困难。然而,你的问题比较广泛,如果你只是想在测试时让你的代码表现不同,我发现这个测试很有用(在VB.Net中)If System.Diagnostics.Debugger.IsAttached Then DoSomething '(例如让一个窗体表现不同) - Neil Dunlop
调试器并不总是需要附加的,有很多情况下你可以在调试模式下编译,但在执行过程中稍后再附加调试器。此外,大多数进程转储工具(比如:用于生产支持的发布版本)都会作为调试器附加。它们与调试模式完全不同,并不能安全地表明程序正在进行测试。 - McGuireV10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接