C# 與 Visual Studio Code 使用者入門Get started with C# and Visual Studio Code

.NET Core 提供快速且模組化的平台,可建立在 Windows、Linux 和 macOS 上執行的應用程式。.NET Core gives you a fast and modular platform for creating applications that run on Windows, Linux, and macOS. 搭配使用 Visual Studio Code 與 C# 擴充功能,以取得具備 C# IntelliSense (智慧型程式碼完成) 與偵錯完整支援的強大編輯體驗。Use Visual Studio Code with the C# extension to get a powerful editing experience with full support for C# IntelliSense (smart code completion) and debugging.

必要條件Prerequisites

  1. 安裝 Visual Studio Code (英文)Install Visual Studio Code.
  2. 安裝 .NET Core SDK (英文)Install the .NET Core SDK.
  3. 安裝適用於 Visual Studio Code 的 C# 擴充功能 (英文)。Install the C# extension for Visual Studio Code. 如需如何在 Visual Studio Code 上安裝擴充功能的詳細資訊,請參閱 VS Code 擴充功能市集 (英文)。For more information about how to install extensions on Visual Studio Code, see VS Code Extension Marketplace.

Hello WorldHello World

讓我們在 .NET Core 上開始進行簡單的 "Hello World" 程式:Let's get started with a simple "Hello World" program on .NET Core:

  1. 開啟專案:Open a project:

    • 開啟 Visual Studio Code。Open Visual Studio Code.

    • 按一下左側功能表上的 [檔案總管] 圖示,然後按一下 [開啟資料夾]。Click on the Explorer icon on the left menu and then click Open Folder.

    • 從主要功能表中選取 [檔案] > [開啟資料夾],以開啟您想要放置 C# 專案的資料夾,然後按一下 [選取資料夾]。Select File > Open Folder from the main menu to open the folder you want your C# project to be in and click Select Folder. 針對本範例,我們將為專案建立一個名為 HelloWorld 的資料夾。For our example, we're creating a folder for our project named HelloWorld.

      Visual Studio Code 開啟資料夾

  2. 初始化 C# 專案:Initialize a C# project:

    • 從主要功能表中選取 [檢視] > [整合式終端機],以從 Visual Studio Code 開啟 [整合式終端機]。Open the Integrated Terminal from Visual Studio Code by selecting View > Integrated Terminal from the main menu.

    • 在終端機視窗中,輸入 dotnet new consoleIn the terminal window, type dotnet new console.

    • 此命令會在您的資料夾中建立已撰寫簡單 "Hello World" 程式的 Program.cs 檔案,以及名為 HelloWorld.csproj 的 C# 專案檔。This command creates a Program.cs file in your folder with a simple "Hello World" program already written, along with a C# project file named HelloWorld.csproj.

      DotNet 新增命令

  3. 解析組建資產:Resolve the build assets:

    • 針對 .NET Core 1.x,鍵入 dotnet restoreFor .NET Core 1.x, type dotnet restore. 執行 dotnet restore 可讓您存取建置專案所需的必要 .NET Core 封裝。Running dotnet restore gives you access to the required .NET Core packages that are needed to build your project.

      DotNet 還原命令

      注意

      從 .NET Core 2.0 SDK 開始,您不需要執行 dotnet restore,因為所有需要進行還原的命令 (例如 dotnet newdotnet builddotnet run) 都會以隱含方式執行它。Starting with .NET Core 2.0 SDK, you don't have to run dotnet restore because it's run implicitly by all commands that require a restore to occur, such as dotnet new, dotnet build and dotnet run. 它在執行明確還原有意義的某些情況下仍然是有效的命令,例如 Azure DevOps Services 中的持續整合組建,或在需要明確控制還原進行時間的建置系統中。It's still a valid command in certain scenarios where doing an explicit restore makes sense, such as continuous integration builds in Azure DevOps Services or in build systems that need to explicitly control the time at which the restore occurs.

  4. 執行 "Hello World" 程式︰Run the "Hello World" program:

    • 輸入 dotnet runType dotnet run.

      DotNet 執行命令

您也可以觀看簡短的影片教學課程,以取得 Windows (英文)macOS (英文)Linux (英文) 上的進一步設定說明。You can also watch a short video tutorial for further setup help on Windows, macOS, or Linux.

偵錯Debug

  1. 按一下 Program.cs 來開啟它。Open Program.cs by clicking on it. 在 Visual Studio Code 中第一次開啟 C# 檔案時,會在編輯器中載入 OmniSharpThe first time you open a C# file in Visual Studio Code, OmniSharp loads in the editor.

    開啟 Program.cs 檔案

  2. Visual Studio Code 應該會提示您新增遺失的資產,以建置和偵錯您的應用程式。Visual Studio Code should prompt you to add the missing assets to build and debug your app. 選取 [是]。Select Yes.

    遺失資產的提示

  3. 若要開啟 [偵錯] 檢視,請按一下左側功能表上的 [偵錯] 圖示。To open the Debug view, click on the Debugging icon on the left side menu.

    在 Visual Studio Code 中開啟 [偵錯] 索引標籤

  4. 尋找窗格頂端的綠色箭頭。Locate the green arrow at the top of the pane. 請確定它旁邊的下拉式清單已選取 .NET Core Launch (console)Make sure the drop-down next to it has .NET Core Launch (console) selected.

    在 Visual Studio Code 中選取 .NET Core

  5. 按一下第 9 行旁邊的 [編輯器邊界] (編輯器中行號左側空白處),將中斷點新增至您的專案,或將文字游標移至編輯器中的第 9 行,然後按 F9 鍵。Add a breakpoint to your project by clicking on the editor margin, which is the space on the left of the line numbers in the editor, next to line 9, or move the text cursor onto line 9 in the editor and press F9.

    設定中斷點

  6. 若要開始偵錯,請選取 F5 或綠色箭頭。To start debugging, select F5 or the green arrow. 當偵錯程式到達您在上一個步驟中設定的中斷點時,它會停止您程式的執行。The debugger stops execution of your program when it reaches the breakpoint you set in the previous step.

    • 進行偵錯時,您可以在左上角窗格中檢視您的本機變數或使用偵錯主控台。While debugging, you can view your local variables in the top left pane or use the debug console.
  7. 選取頂端的藍色箭頭以繼續偵錯,或選取頂端的紅色正方形以停止偵錯。Select the blue arrow at the top to continue debugging, or select the red square at the top to stop.

    在 Visual Studio Code 中執行和偵錯

提示

如需在 Visual Studio Code 中使用 OmniSharp 進行 .NET Core 偵錯的詳細資訊與疑難排解祕訣,請參閱 Instructions for setting up the .NET Core debugger (設定 .NET Core 偵錯工具的指示)。For more information and troubleshooting tips on .NET Core debugging with OmniSharp in Visual Studio Code, see Instructions for setting up the .NET Core debugger.

新增類別Add a class

  1. 若要新增類別,請在「VSCode 總管」中按一下滑鼠右鍵,然後選取 [新增檔案]。To add a new class right-click in the VSCode Explorer and select New File. 這會在您於 VSCode 中開啟的資料夾內新增檔案。This adds a new file to the folder you have open in VSCode.

  2. 將檔案命名為 MyClass.csName your file MyClass.cs. 您必須在結尾加上 .cs 副檔名來儲存它,系統才能將它辨識為 csharp 檔案。You must save it with a .cs extension at the end for it to be recognized as a csharp file.

  3. 新增下方程式碼來建立您的第一個類別。Add the code below to create your first class. 請務必包含正確的命名空間,如此您才能夠從 Program.cs 檔案參考它。Make sure to include the correct namespace so you can reference it from your Program.cs file.

    using System;
    
    namespace HelloWorld
    {
        public class MyClass
        {
            public string ReturnMessage()
            {
                return "Happy coding!";
            }
        }
    }
    
  4. 新增下方程式碼以從 Program.cs 中的主要方法呼叫您的新類別。Call your new class from your main method in Program.cs by adding the code below.

    using System;
    
    namespace HelloWorld
    {
        class Program
        {
            static void Main(string[] args)
            {
                MyClass c1 = new MyClass();
                Console.WriteLine($"Hello World! {c1.ReturnMessage()}");
            }
        }
    }
    
  5. 儲存變更,然後重新執行您的程式。Save your changes and run your program again. 應該會顯示含有所附加字串的新訊息。The new message should appear with the appended string.

    > dotnet run
    Hello World! Happy coding!
    

常見問題集FAQ

我缺少在 Visual Studio Code 中建置及偵錯 C# 所需的資產。I'm missing required assets to build and debug C# in Visual Studio Code. 我的偵錯工具顯示「沒有組態」。My debugger says "No Configuration."

Visual Studio Code C# 延伸模組可為您產生用於建置和偵錯的資產。The Visual Studio Code C# extension can generate assets to build and debug for you. Visual Studio Code 會在您第一次開啟 C# 專案時,提示您產生這些資產。Visual Studio Code prompts you to generate these assets when you first open a C# project. 如果您當時未產生資產,仍可以透過開啟 [命令選擇區] ([檢視] > [命令選擇區]),然後鍵入 ">.NET:Generate Assets for Build and Debug" 來執行此命令。If you didn't generate assets then, you can still run this command by opening the Command Palette (View > Command Palette) and typing ">.NET: Generate Assets for Build and Debug". 選取此選項會產生您所需的 .vscode、launch.json 和 tasks.json 組態檔。Selecting this generates the .vscode, launch.json, and tasks.json configuration files that you need.

另請參閱See also