2011-11-23 70 views
3

考慮下面的代碼:與Debug.Assert的條件編譯

#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. 這是少寫代碼。
+0

Debug.Assert的勝利對我來說 –

+1

說實話我在釋放模式,而奉送的99%的時間每一次,所以很少用或者 –

+0

@jk:真。在這種情況下,這是針對遊戲的,所以儘可能避免像這樣的檢查,但在調試時儘快得到錯誤是可以的。 –

回答

4

您可以隨時使用Debug.Assert的(),因爲這個類與DEBUG符合條件,以及:

[Conditional("Debug")] 

表示到編譯器,一個方法調用或屬性應該是 忽略除非定義了指定的條件編譯符號。

ConditionalAttribute應用於 Debug和Trace類中定義的方法。
http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx

+1

+1感謝您的信息,儘管我已經意識到[ConditionalAttribute](http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx)(編輯清楚) 。 –

+0

太棒了,那麼我會用你的「3.這是更少的代碼寫。」作爲Debug.Assert()的主要原因:-) – CodeZombie

+0

謝謝,我會把它打開一段時間,看看有沒有其他答案(沒有忘記接受)。 –