教學課程:了解如何使用 Visual Studio 對 C# 程式碼進行偵錯Tutorial: Learn to debug C# code using Visual Studio

本文以逐步解說介紹 Visual Studio 偵錯工具的功能。This article introduces the features of the Visual Studio debugger in a step-by-step walkthrough. 如果您希望檢視偵錯工具功能的概要,請參閱偵錯工具簡介If you want a higher-level view of the debugger features, see First look at the debugger. 當您「偵錯您的應用程式」**,通常表示您正在執行附加偵錯工具的應用程式。When you debug your app, it usually means that you are running your application with the debugger attached. 執行此作業時,偵錯工具會提供許多方式來查看您程式碼所執行的功能。When you do this, the debugger provides many ways to see what your code is doing while it runs. 您可以逐步執行程式碼並查看儲存在變數中的值、可以設定變數的監看式以查看值變更、可以檢查程式碼的執行路徑,查看是否正在執行程式碼的分支,依此類推。You can step through your code and look at the values stored in variables, you can set watches on variables to see when values change, you can examine the execution path of your code, see whether a branch of code is running, and so on. 如果這是您第一次嘗試偵錯程式碼,您可能需要先閱讀適用於徹底初學者偵錯,再瀏覽本文。If this is the first time that you've tried to debug code, you may want to read Debugging for absolute beginners before going through this article.

雖然示範應用程式是 C#,但大多數功能也適用於 C++、Visual Basic、F#、Python、JavaScript 及 Visual Studio 支援的其他語言 (F# 不支援「編輯後繼續」。Although the demo app is C#, most of the features are applicable to C++, Visual Basic, F#, Python, JavaScript, and other languages supported by Visual Studio (F# does not support Edit-and-continue. F# 和 JavaScript 不支援 [自動變數]**** 視窗)。F# and JavaScript do not support the Autos window). 螢幕擷取畫面則使用 C# 表示。The screenshots are in C#.

在本教學課程中,您將:In this tutorial, you will:

  • 啟動偵錯工具,並叫用中斷點。Start the debugger and hit breakpoints.
  • 了解命令以在偵錯工具中逐步執行程式碼Learn commands to step through code in the debugger
  • 檢查資料提示和偵錯工具視窗中的變數Inspect variables in data tips and debugger windows
  • 檢查呼叫堆疊Examine the call stack

先決條件Prerequisites

您必須安裝 Visual Studio 2019 和 .Net Core 跨平臺開發工作負載。You must have Visual Studio 2019 installed and the .NET Core cross-platform development workload.

您必須安裝 Visual Studio 2017 和 .Net Core 跨平臺開發工作負載。You must have Visual Studio 2017 installed and the .NET Core cross-platform development workload.

如果您尚未安裝 Visual Studio,請前往 Visual Studio 下載頁面免費進行安裝。If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

如果您尚未安裝 Visual Studio,請前往 Visual Studio 下載頁面免費進行安裝。If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

如果您需要安裝工作負載,但已經有 Visual Studio,請移至 [工具 > ] [取得工具和功能 ...],這會開啟 Visual Studio 安裝程式。If you need to install the workload but already have Visual Studio, go to Tools > Get Tools and Features..., which opens the Visual Studio Installer. Visual Studio 安裝程式即會啟動。The Visual Studio Installer launches. 選擇 [ .Net Core 跨平臺開發] 工作負載,然後選擇 [修改]。Choose the .NET Core cross-platform development workload, then choose Modify.

建立專案Create a project

首先,您將建立 .NET Core 主控台應用程式專案。First, you'll create a .NET Core console application project. 在您新增任何項目之前,專案類型會隨附您需要的所有範本檔案!The project type comes with all the template files you'll need, before you've even added anything!

  1. 開啟 Visual Studio 2017。Open Visual Studio 2017.

  2. 從頂端功能表列中,選擇 [檔案]** [新增]** > ** [專案]** > ****。From the top menu bar, choose File > New > Project.

  3. 在 [新增專案]**** 對話方塊的左窗格中,展開 [C#]****,然後選擇 [.NET Core]****。In the New Project dialog box in the left pane, expand C#, and then choose .NET Core. 在中間窗格中,選擇 [主控台應用程式 (.NET Core)]****。In the middle pane, choose Console App (.NET Core). 然後將專案命名為「開始使用 -進行調試」。Then name the project get-started-debugging.

    如果您沒有看到 [主控台應用程式 (.NET Core)]**** 專案範本,請在 [新增專案]**** 對話方塊的左窗格中,選擇 [開啟 Visual Studio 安裝程式]**** 連結。If you don't see the Console App (.NET Core) project template, choose the Open Visual Studio Installer link in the left pane of the New Project dialog box.

    Visual Studio 安裝程式即會啟動。The Visual Studio Installer launches. 選擇 [.NET Core 跨平台開發]**** 工作負載,然後選擇 [修改]****。Choose the .NET Core cross-platform development workload, and then choose Modify.

  1. 開啟 Visual Studio 2019。Open Visual Studio 2019.

    如果 [開始] 視窗未開啟,請選擇 [ >檔案 ] [啟動視窗]If the start window is not open, choose File > Start Window.

  2. 在 [開始] 視窗中,選擇 [建立新專案]。On the start window, choose Create a new project.

  3. 在 [建立新專案]**** 視窗的搜尋方塊中輸入或鍵入 ASP.NET**。On the Create a new project window, enter or type console in the search box. 接下來,從語言清單中選擇 C#,然後從平台清單中選擇 WindowsNext, choose C# from the Language list, and then choose Windows from the Platform list.

    在您套用語言和平台的篩選條件之後,請選擇 [主控台應用程式 (.NET Core)]**** 範本,然後選擇 [下一步]****。After you apply the language and platform filters, choose the Console App (.NET Core) template, and then choose Next.

    選擇主控台應用程式的 c # 範本(.NET Core)

    注意

    如果您未看到 [主控台應用程式 (.NET Core)]**** 範本,您可以從 [建立新專案]**** 視窗中安裝。If you do not see the Console App (.NET Core) template, you can install it from the Create a new project window. 在 [找不到您要找的資料嗎?]**** 訊息中,選擇 [安裝更多工具和功能]**** 連結。In the Not finding what you're looking for? message, choose the Install more tools and features link. 接下來,在 Visual Studio 安裝程式中選擇 .NET Core 跨平台開發工作負載。Then, in the Visual Studio Installer, choose the .NET Core cross-platform development workload.

  4. 在 [設定您的新專案] 視窗中,于 [專案名稱] 方塊中鍵入或輸入GetStartedDebuggingIn the Configure your new project window, type or enter GetStartedDebugging in the Project name box. 然後選擇 [建立]。Then, choose Create.

    Visual Studio 會隨即開啟您的新專案。Visual Studio opens your new project.

建立應用程式Create the application

  1. Program.cs中,以下列程式碼取代所有的預設程式碼:In Program.cs, replace all of the default code with the following code instead:

    using System;
    class ArrayExample
    {
        static void Main()
        {
            char[] letters = { 'f', 'r', 'e', 'd', ' ', 's', 'm', 'i', 't', 'h'};
            string name = "";
            int[] a = new int[10];
            for (int i = 0; i < letters.Length; i++)
            {
                name += letters[i];
                a[i] = i + 1;
                SendMessage(name, a[i]);
            }
            Console.ReadKey();
        }
        static void SendMessage(string name, int msg)
        {
            Console.WriteLine("Hello, " + name + "! Count to " + msg);
        }
    }
    

啟動偵錯工具!Start the debugger!

  1. F5debug > 開始進行調試),或在調試工具列中,按 [開始調試] 按鈕開始進行調試Press F5 (Debug > Start Debugging) or the Start Debugging button Start Debugging in the Debug Toolbar.

    F5 鍵會啟動應用程式並將偵錯工具附加至應用程式處理序,但目前我們還沒有做任何特別動作來檢查程式碼。F5 starts the app with the debugger attached to the app process, but right now we haven't done anything special to examine the code. 因此應用程式只會載入,且您會看到主控台輸出。So the app just loads and you see the console output.

    Hello, f! Count to 1
    Hello, fr! Count to 2
    Hello, fre! Count to 3
    Hello, fred! Count to 4
    Hello, fred ! Count to 5
    Hello, fred s! Count to 6
    Hello, fred sm! Count to 7
    Hello, fred smi! Count to 8
    Hello, fred smit! Count to 9
    Hello, fred smith! Count to 10
    

    在本教學課程中,我們將使用偵錯工具仔細查看這個應用程式,並了解偵錯工具功能。In this tutorial, we'll take a closer look at this app using the debugger and get a look at the debugger features.

  2. 按下紅色的停止調試程式按鈕(Shift + F5)來停止偵錯工具。Stop the debugger by pressing the red stop Stop Debugging button (Shift + F5).

  3. 在主控台視窗中,按下按鍵關閉主控台視窗。In the console window, press a key to close the console window.

設定中斷點,並啟動偵錯工具Set a breakpoint and start the debugger

  1. Main 函式的 for 迴圈中,按一下下列程式碼行的左邊界來設定中斷點:In the for loop of the Main function, set a breakpoint by clicking the left margin of the following line of code:

    name += letters[i];

    在您設定中斷點的位置會出現紅色圓圈中斷點A red circle Breakpoint appears where you set the breakpoint.

    中斷點是可靠的調試最基本和基本的功能之一。Breakpoints are one of the most basic and essential features of reliable debugging. 中斷點會指出 Visual Studio 應暫停程式碼執行的地方,如此一來您可以查看變數的值或記憶體的行為,或查看程式碼分支是否正在執行。A breakpoint indicates where Visual Studio should suspend your running code so you can take a look at the values of variables, or the behavior of memory, or whether or not a branch of code is getting run.

  2. F5或 [開始調試程式] 按鈕開始進行偵測,應用程式會啟動,而偵錯工具會執行到您設定中斷點的程式程式碼。Press F5 or the Start Debugging button Start Debugging, the app starts, and the debugger runs to the line of code where you set the breakpoint.

    設定並叫用中斷點

    黃色箭號表示偵錯工具暫停時的陳述式,這也表示會在相同的點暫停執行應用程式 (尚未執行此陳述式)。The yellow arrow represents the statement on which the debugger paused, which also suspends app execution at the same point (this statement has not yet executed).

    如果尚未執行應用程式,則 F5 鍵會啟動偵錯工具並在第一個中斷點停止。If the app is not yet running, F5 starts the debugger and stops at the first breakpoint. 否則,F5 鍵會繼續執行應用程式到下一個中斷點。Otherwise, F5 continues running the app to the next breakpoint.

    如果您知道要詳細檢查的程式碼行或程式碼區段,則中斷點是一個很有用的功能。Breakpoints are a useful feature when you know the line of code or the section of code that you want to examine in detail. 如需您可以設定的不同中斷點類型(例如條件式中斷點)的詳細資訊,請參閱使用中斷點For information on the different types of breakpoints you can set, such as conditional breakpoints, see Using breakpoints.

在大部分情況下,我們會在這裡使用鍵盤快速鍵,因為這是在偵錯工具中快速執行應用程式的好方法 (功能表命令等對等命令會顯示在括弧內)。Mostly, we use the keyboard shortcuts here, because it's a good way to get fast at executing your app in the debugger (equivalent commands such as menu commands are shown in parentheses).

  1. name += letters[i]語句上暫停時,將滑鼠停留letters在變數上,您會看到它是預設值,也就是陣列中第一個char[10]元素的值。While paused on the name += letters[i] statement, hover over the letters variable and you see it's default value, the value of the first element in the array, char[10].

    可讓您檢查變數的功能是偵錯工具最實用功能之一,而且有不同的方法來完成此作業。Features that allow you to inspect variables are one of the most useful features of the debugger, and there are different ways to do it. 通常當您嘗試偵錯問題時,您會嘗試確定變數是否會儲存您希望其在特定時間具有的值。Often, when you try to debug an issue, you are attempting to find out whether variables are storing the values that you expect them to have at a particular time.

  2. 展開letters變數以查看其屬性,其中包括變數包含的所有元素。Expand the letters variable to see its properties, which include all the elements that the variable contains.

    查看資料提示View a data tip

  3. 接下來,將滑鼠name停留在變數上,您會看到其目前的值為空字串。Next, hover over the name variable, and you see its current value, an empty string.

  4. 按下f10鍵(或選擇 [ Debug >] [不進入函SendMessage式])以前進至方法呼叫,然後再按一次f10Press F10 (or choose Debug > Step Over) twice to advance to the SendMessage method call, and then press F10 one more time.

    F10 將偵錯工具前移至下一個語句,而不需要逐步執行應用程式程式碼中的函式或方法(程式碼仍會執行)。F10 advances the debugger to the next statement without stepping into functions or methods in your app code (the code still executes). 藉由在SendMessage方法呼叫上按下 F10 鍵,我們略過了SendMessage的程式碼(也許我們目前不感興趣)。By pressing F10 on the SendMessage method call, we skipped over the implementation code for SendMessage (which maybe we're not interested in right now).

  5. 按下F10(或 > [逐一檢查] [逐步執行]),透過for迴圈逐一查看數次、在中斷點上再次暫停, name並在每次檢查其值時將滑鼠停留在變數上。Press F10 (or Debug > Step Over) a few times to iterate several times through the for loop, pausing again at the breakpoint, and hovering over the name variable each time to check its value.

    查看資料提示View a data tip

    變數的for值會隨著迴圈的每個反復專案而變更,顯示的f值、 frthen、 frethen 等等。The value of the variable changes with each iteration of the for loop, showing values of f, then fr, then fre, and so on. 若要在這種情況下,讓偵錯工具更快進入迴圈,您可以改為按F5或選擇 [ > 檢查] [繼續]),這會將您帶到中斷點,而不是下一個語句。To advance the debugger through the loop faster in this scenario, you can press F5 (or choose Debug > Continue) instead, which advances you to the breakpoint instead of the next statement.

    很多時候,您會希望在偵錯時快速檢查變數的屬性值,以查看其是否如您預期的儲存值,而資料提示是很適合的方法。Often, when debugging, you want a quick way to check property values on variables, to see whether they are storing the values that you expect them to store, and the data tips are a good way to do it.

  6. for Main方法的迴圈中仍然暫停時,請按下F11鍵(或選擇 [ Debug >] [逐步執行] SendMessage ),直到您在方法呼叫暫停為止。While still paused in the for loop in the Main method, press F11 (or choose Debug > Step Into) until you pause at the SendMessage method call.

    您應該會在這行程式碼中:You should be at this line of code:

    SendMessage(name, a[i]);

  7. 再按一次F11鍵,逐步執行SendMessage方法。Press F11 one more time to step into the SendMessage method.

    黃色指標會前進到SendMessage方法中。The yellow pointer advances into the SendMessage method.

    使用 F11 逐步執行程式碼Use F11 to Step Into code

    F11 鍵是逐步執行命令,可將應用程式執行一次往前推進一個陳述式。F11 is the Step Into command and advances the app execution one statement at a time. F11 鍵是以最詳細的方式檢查執行流程的好方法F11 is a good way to examine the execution flow in the most detail. 根據預設,偵錯工具會略過非使用者程式碼 (如果您想要更多的詳細資料,請參閱 Just My Code)。By default, the debugger skips over non-user code (if you want more details, see Just My Code).

    假設您已經完成檢查SendMessage方法,而您想要離開方法但停留在偵錯工具中。Let's say that you are done examining the SendMessage method, and you want to get out of the method but stay in the debugger. 您可以使用 [跳離函式]**** 命令完成這項動作。You can do this using the Step Out command.

  8. Shift + F11 (或Debug > 跳出)。Press Shift + F11 (or Debug > Step Out).

    此命令會繼續執行應用程式(並使偵錯工具前進),直到目前的方法或函式傳回為止。This command resumes app execution (and advances the debugger) until the current method or function returns.

    您應該會回到for Main方法中的迴圈,在SendMessage方法呼叫中暫停。You should be back in the for loop in the Main method, paused at the SendMessage method call. 如需在程式碼中移動不同方式的詳細資訊,請參閱在偵錯工具中流覽程式碼For more information on different ways to move through your code, see Navigate code in the debugger.

  1. F5再次前進至中斷點。Press F5 to advance to the breakpoint again.

  2. 在 [程式碼編輯器] 中,向下移動Console.WriteLine並將滑鼠SendMessage游標暫留在方法中的方法上,直到按一下 [執行 ] 按鈕的綠色回合,才會出現在左邊。In the code editor, scroll down and hover over the Console.WriteLine method in the SendMessage method until the green Run to Click button Run to Click appears on the left. 按鈕的工具提示會顯示「執行到這裡」。The tooltip for the button shows "Run execution to here".

    使用 [執行至] 按一下功能Use the Run to Click feature

    注意

    [執行至點選處]**** 按鈕是 Visual Studio 2017Visual Studio 2017 的新功能。The Run to Click button is new in Visual Studio 2017Visual Studio 2017. (如果您沒有看到綠色箭號按鈕,請在此範例中使用F11鍵,讓偵錯工具前進到正確的位置)。(If you don't see the green arrow button, use F11 in this example instead to advance the debugger to the right place.)

  3. 按一下 [執行] 按一下![執行] 按鈕,然後按一下Click the Run to Click button Run to Click.

    偵錯工具會前進至Console.WriteLine方法。The debugger advances to the Console.WriteLine method.

    使用此按鈕類似於設定暫時中斷點。Using this button is similar to setting a temporary breakpoint. [執行至點選處]**** 方便您在應用程式程式碼的可見區域內快速瀏覽 (您可以按一下任何開啟的檔案)。Run to Click is handy for getting around quickly within a visible region of app code (you can click in any open file).

快速重新啟動您的應用程式Restart your app quickly

按一下 [偵錯工具] 工具列中的 [重新開機重新開機應用程式] 按鈕(Ctrl + Shift + F5)。Click the Restart Restart App button in the Debug Toolbar (Ctrl + Shift + F5).

相對於停止應用程式並重新啟動偵錯工具,按下 [重新啟動]**** 可讓您節省時間。When you press Restart, it saves time versus stopping the app and restarting the debugger. 偵錯工具會在執行程式碼叫用的第一個中斷點處暫停。The debugger pauses at the first breakpoint that is hit by executing code.

偵錯工具會在您先前在for迴圈內設定的中斷點處停止。The debugger stops again at the breakpoint you previously set inside the for loop.

使用 [自動變數] 和 [區域變數] 視窗來檢查變數Inspect variables with the Autos and Locals windows

  1. 查看程式碼編輯器底部的 [自動變數]**** 視窗。Look at the Autos window at the bottom of the code editor.

    如果已關閉,請在偵錯工具中選擇 [ Debug > Windows > 自動變數] 來開啟它。If it is closed, open it while paused in the debugger by choosing Debug > Windows > Autos.

    在 [自動變數]**** 視窗中,您會看到變數及其目前的值。In the Autos window, you see variables and their current value. [自動變數]**** 視窗會顯示在目前行或前述行 (請查看文件以了解語言特定行為) 中使用的所有變數。The Autos window shows all variables used on the current line or the preceding line (Check documentation for language-specific behavior).

  2. 接下來,在 [自動變數]**** 視窗旁的索引標籤中查看 [區域變數]**** 視窗。Next, look at the Locals window, in a tab next to the Autos window.

  3. 展開letters變數以顯示其包含的元素。Expand the letters variable to show the elements that it contains.

    檢查 [區域變數] 視窗中的變數Inspect variables in the Locals Window

    [區域變數]**** 視窗會顯示位在目前範圍中的變數,即為目前執行內容。The Locals window shows you the variables that are in the current scope, that is, the current execution context.

設定監看式Set a watch

  1. 在主要的 [程式碼編輯器] 視窗中, name以滑鼠右鍵按一下變數,然後選擇 [加入監看式]In the main code editor window, right-click the name variable and choose Add Watch.

    [監看式]**** 視窗隨即在程式碼編輯器底部開啟。The Watch window opens at the bottom of the code editor. 您可以使用 [監看式]**** 視窗來指定您要留意的變數 (或運算式)。You can use a Watch window to specify a variable (or an expression) that you want to keep an eye on.

    現在,您已在name變數上設定監看式,而且當您在偵錯工具中移動時,可以看到其值變更。Now, you have a watch set on the name variable, and you can see its value change as you move through the debugger. 不同於其他變數視窗,[監看式]**** 視窗一律會顯示所監看的變數 (它們在超出範圍時會呈現灰色)。Unlike the other variable windows, the Watch window always shows the variables that you are watching (they're grayed out when out of scope).

檢查呼叫堆疊Examine the call stack

  1. for 迴圈中暫停時,按一下 [呼叫堆疊]**** 視窗,此視窗預設會在右下方的窗格中開啟。While paused in the for loop, click the Call Stack window, which is by default open in the lower right pane.

    如果已關閉,請在偵錯工具中選擇 [ Debug > Windows > 呼叫堆疊] 來開啟它。If it is closed, open it while paused in the debugger by choosing Debug > Windows > Call Stack.

  2. 按幾下F11鍵,直到您看到偵錯工具在SendMessage方法中暫停為止。Click F11 a few times until you see the debugger pause in the SendMessage method. 查看 [呼叫堆疊]**** 視窗。Look at the Call Stack window.

    檢查呼叫堆疊Examine the call stack

    [呼叫堆疊]**** 視窗會顯示方法和函式的呼叫順序。The Call Stack window shows the order in which methods and functions are getting called. 第一行會顯示目前的函式 (此應用程式中的 SendMessage 方法)。The top line shows the current function (the SendMessage method in this app). 第二行會顯示已從 Main 方法呼叫 SendMessage,依此類推。The second line shows that SendMessage was called from the Main method, and so on.

    注意

    [呼叫堆疊]**** 視窗類似於某些 IDE (例如 Eclipse) 中的 [偵錯] 檢視方塊。The Call Stack window is similar to the Debug perspective in some IDEs like Eclipse.

    呼叫堆疊是檢查並了解應用程式執行流程的好方法。The call stack is a good way to examine and understand the execution flow of an app.

    您可以按兩下某一行的程式碼來查看其原始程式碼,這也會變更偵錯工具所檢查的目前範圍。You can double-click a line of code to go look at that source code and that also changes the current scope being inspected by the debugger. 此動作不會讓偵錯工具往前推進。This action does not advance the debugger.

    您也可以從 [呼叫堆疊]**** 視窗使用滑鼠右鍵功能表來執行其他動作。You can also use right-click menus from the Call Stack window to do other things. 例如,您可以在指定的函式中插入中斷點,使用 [執行至游標處]**** 讓偵錯工具往前推進,並檢查原始程式碼。For example, you can insert breakpoints into specified functions, advance the debugger using Run to Cursor, and go examine source code. 如需詳細資訊,請參閱如何:檢查呼叫堆疊For more information, see How to: Examine the Call Stack.

變更執行流程Change the execution flow

  1. F11兩次以執行Console.WriteLine方法。Press F11 twice to run the Console.WriteLine method.

  2. 當偵錯工具在SendMessage方法呼叫中暫停時,使用滑鼠來抓取左邊的黃色箭號(執行指標),並將黃色箭號向上移動一行。 Console.WriteLineWith the debugger paused in the SendMessage method call, use the mouse to grab the yellow arrow (the execution pointer) on the left and move the yellow arrow up one line, back to Console.WriteLine.

  3. F11Press F11.

    偵錯工具會重新執行 Console.WriteLine 方法 (您會在主控台視窗輸出中看到)。The debugger reruns the Console.WriteLine method (you see this in the console window output).

    藉由變更執行流程,您可以執行一些作業,例如測試不同的程式碼執行路徑,或重新執行程式碼而不重新啟動偵錯工具。By changing the execution flow, you can do things like test different code execution paths or rerun code without restarting the debugger.

    警告

    您通常需要謹慎使用這項功能,您會在工具提示中看到一則警告。Often you need to be careful with this feature, and you see a warning in the tooltip. 也可能會看到其他警告。You may see other warnings, too. 移動指標無法將應用程式還原成先前的應用程式狀態。Moving the pointer cannot revert your application to an earlier app state.

  4. F5 鍵繼續執行應用程式。Press F5 to continue running the app.

    恭喜您完成此教學課程!Congratulations on completing this tutorial!

後續步驟Next steps

在本教學課程中,您已了解如何啟動偵錯工具、逐步執行程式碼,以及檢查變數。In this tutorial, you've learned how to start the debugger, step through code, and inspect variables. 建議您進一步查看偵錯工具功能,以及詳細資訊的連結。You may want to get a high-level look at debugger features along with links to more information.