Debug.Assert与条件编译

时间:2011-11-23 12:26:00

标签: c# debugging conditional-compilation

请考虑以下代码:

#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. 写的代码较少。

1 个答案:

答案 0 :(得分:4)

您始终可以使用Debug.Assert(),因为此类也符合DEBUG条件:

[Conditional("Debug")]
  

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

     

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