練習 - 記錄和追蹤
既然已開始開發應用程式,很適合將更多的診斷新增至邏輯,以協助開發人員新增功能。 我們可以使用偵錯診斷的新知識來完成這項工作。
寫入偵錯主控台
在我們針對應用程式進行偵錯時,讓我們先新增更多的偵錯工具。 當應用程式在偵錯期間執行時,額外的診斷將能協助您診斷該應用程式。
在 Program.cs
檔案的頂端,我們將新增 using
陳述式以帶入 System.Diagnostics
,如此便可使用 Debug
方法。
using System.Diagnostics;
在 Fibonacci
方法的開頭新增 WriteLine
陳述式,以在您對程式碼進行偵錯時更加清楚。
Debug.WriteLine($"Entering {nameof(Fibonacci)} method");
Debug.WriteLine($"We are looking for the {n}th number");
我們可以在 for
迴圈的結尾處印出每個值。 我們也可以使用 WriteIf
或 WriteLineIf
,只在 for 迴圈結尾的 sum
為 1 時才新增列印行,即可使用條件式列印陳述式:
for (int i = 2; i <= n; i++)
{
sum = n1 + n2;
n1 = n2;
n2 = sum;
Debug.WriteLineIf(sum == 1, $"sum is 1, n1 is {n1}, n2 is {n2}");
}
對應用程式進行偵錯,而您應該會取得下列輸出:
Entering Fibonacci method
We are looking for the 5th number
sum is 1, n1 is 1, n2 is 1
使用判斷提示檢查條件
在某些情況下,建議您在不符合特定條件時停止整個執行中應用程式。 使用 Debug.Assert
可讓您檢查條件,並輸出有關應用程式狀態的其他資訊。 讓我們在 return 陳述式正前方新增一個檢查,以確保 n2 為 5。
// If n2 is 5 continue, else break.
Debug.Assert(n2 == 5, "The return value is not 5 and it should be.");
return n == 0 ? n1 : n2;
我們的應用程式邏輯已經正確,因此,讓我們將 Fibonacci(5);
更新為 Fibonacci(6);
,這將產生不同的結果。
針對應用程式進行偵錯。 當 Debug.Assert
在程式碼中執行時,偵錯工具會停止應用程式,讓您可以檢查變數、監看式視窗、呼叫堆疊等。 其也會將訊息輸出到偵錯主控台。
---- DEBUG ASSERTION FAILED ----
---- Assert Short Message ----
The return value is not 5 and it should be.
---- Assert Long Message ----
at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3
停止偵錯,然後在終端輸中入下列命令,以在不進行偵錯的情況下執行應用程式。
dotnet run
請注意,在判斷提示失敗並將資訊記錄到應用程式輸出之後,應用程式即會終止。
Process terminated. Assertion failed.
The return value is not 5 and it should be.
at Program.<<Main>$>g__Fibonacci|0_0(Int32 n) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 23
at Program.<Main>$(String[] args) in C:\Users\Jon\Desktop\DotNetDebugging\Program.cs:line 3
現在,讓我們在終端中使用下列命令,在 Release
設定中執行應用程式。
dotnet run --configuration Release
應用程式已成功執行到完成,因為我們已不再處於 Debug
設定中。
恭喜,您已使用 .NET 的功能 (包括 Debug.WriteLine
與 Debug.Assert
),成功且有效率地針對程式碼進行偵錯。 做得好!