【问题标题】:Debug.Assert versus conditional compilationDebug.Assert 与条件编译
【发布时间】:2012-01-04 17:51:25
【问题描述】:

考虑下面的代码:

#if DEBUG
    if (Systems.Contains(system))
        throw new InvalidOperationException("System already registered");
#endif

    Debug.Assert(!Systems.Contains(system), "System already registered");

以前我用的是前者,后来我发现了Debug.Assert

我为什么不总是更喜欢Debug.Assert,有什么原因吗?

  1. 仅存在于调试代码中(属性为[Conditional("DEBUG")])。
  2. 在我看来,这更符合我的意图(代码完整性检查,而不是引发稍后处理的异常)。
  3. 编写的代码更少。

【问题讨论】:

  • Debug.Assert 每次都为我赢得胜利
  • 老实说,我宁愿在 99% 的时间里也投入发布模式,所以很少使用任何一种
  • @jk.:是的。在这种情况下,它是针对游戏的,因此如果可能,最好避免进行此类检查,但可以在调试时尽早发现错误。

标签: c# debugging conditional-compilation


【解决方案1】:

你总是可以使用 Debug.Assert(),因为这个类也符合 DEBUG 条件:

[Conditional("Debug")]

向编译器指示方法调用或属性应该是 除非定义了指定的条件编译符号,否则将被忽略。

ConditionalAttribute 应用于定义在 调试和跟踪类。
http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx

【讨论】:

  • +1 感谢您提供的信息,尽管我已经知道ConditionalAttribute(已编辑以明确这一点)。
  • 太好了,所以我会使用您的“3。编写的代码更少。”作为 Debug.Assert() 的主要原因 :-)
  • 谢谢,我会再打开一段时间看看有没有其他回复(别忘了接受)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2010-11-15
  • 2023-03-05
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多