C# 多為實例方法,對象有效狀態隱含假設。公有方法被調用時應驗證假設。條件編譯讓此極簡單:
先寫私有驗證方法,標記 [Conditional("DEBUG")]:
[Conditional("DEBUG")]
private void ImOK() {
Debug.Assert(this != null, "Testing Object State", "this cannot be null");
// More here.
}
每個公有方法調用 ImOK():
public bool ProcessIterations(int numIters) {
ImOK();
Debug.Assert(numIters > 0, "ProcessIterations.", "Iterations must be more than 0");
}
Release 版編譯器自動移除 ImOK 調用。優勢:快速發現對象狀態失效。
列印診斷訊息助定位錯誤。需知 Assert 觸發時發生何事、之前發生何事。最佳方式:在代碼中輸出,易見調用鏈。.NET System.Diagnostics.Debug 提供格式化輸出、分級調試功能。