教學課程:使用 Visual Studio Code 在 macOS 中建立 .NET Core 解決方案Tutorial: Create a .NET Core solution in macOS using Visual Studio Code

本文件提供建立適用於 macOS 之 .NET Core 方案的步驟及工作流程。This document provides the steps and workflow to create a .NET Core solution for macOS. 了解如何建立專案、建立單元測試、使用偵錯工具,以及透過 NuGet 納入協力廠商程式庫。Learn how to create projects, unit tests, use the debugging tools, and incorporate third-party libraries via NuGet.

注意

這篇文章會在 macOS 上使用 Visual Studio CodeThis article uses Visual Studio Code on macOS.

必要條件Prerequisites

安裝 .NET Core SDK (英文)Install the .NET Core SDK. .NET Core SDK 包含 .NET Core 架構和執行階段的最新版本。The .NET Core SDK includes the latest release of the .NET Core framework and runtime.

安裝 Visual Studio Code (英文)Install Visual Studio Code. 在這篇文章的過程中,您也將安裝能改善 .NET Core 開發體驗的 Visual Studio Code 延伸模組。During the course of this article, you also install Visual Studio Code extensions that improve the .NET Core development experience.

請開啟 Visual Studio Code,並按下 F1 來開啟 Visual Studio Code 調色盤,以安裝 Visual Studio Code C# 延伸模組。Install the Visual Studio Code C# extension by opening Visual Studio Code and pressing F1 to open the Visual Studio Code palette. 鍵入 ext install 來查看延伸模組的清單。Type ext install to see the list of extensions. 選取 C# 延伸模組。Select the C# extension. 重新啟動 Visual Studio Code 以啟動延伸模組。Restart Visual Studio Code to activate the extension. 如需詳細資訊,請參閱 Visual Studio Code C# 延伸模組文件For more information, see the Visual Studio Code C# Extension documentation.

開始使用Get started

在本教學課程中,您會建立三個專案︰程式庫專案、該程式庫專案的測試,以及利用程式庫的主控台應用程式。In this tutorial, you create three projects: a library project, tests for that library project, and a console application that makes use of the library. 您可以在 GitHub 的 dotnet/samples 存放庫檢視或下載來源You can view or download the source for this topic at the dotnet/samples repository on GitHub. 如需下載指示,請參閱範例和教學課程For download instructions, see Samples and Tutorials.

啟動 Visual Studio Code。Start Visual Studio Code. 按下 Ctrl+` (倒引號字元),或從功能表中選取 [檢視] > [整合式終端機],以使用 Visual Studio Code 開啟內嵌終端機。Press Ctrl+` (the backquote or backtick character) or select View > Integrated Terminal from the menu to open an embedded terminal in Visual Studio Code. 如果您想要在 Visual Studio Code 外部工作,則仍然可以使用總管 [在命令提示字元中開啟] 命令 (Mac 或 Linux 上的 [在終端機中開啟]) 來開啟外部殼層。You can still open an external shell with the Explorer Open in Command Prompt command (Open in Terminal on Mac or Linux) if you prefer to work outside of Visual Studio Code.

請從建立方案檔開始,而方案檔是作為一或多個 .NET Core 專案的容器。Begin by creating a solution file, which serves as a container for one or more .NET Core projects. 在終端機中,執行dotnet new命令以在名為黃金的新資料夾內建立新的方案 In the terminal, run the dotnet new command to create a new solution golden.sln inside a new folder named golden:

dotnet new sln -o golden

流覽至新的 [黃金] 資料夾,然後執行下列命令來建立程式庫專案,這會在library資料夾中產生兩個檔案,即連結庫 .csprojClass1.csNavigate to the new golden folder and execute the following command to create a library project, which produces two files,library.csproj and Class1.cs, in the library folder:

dotnet new classlib -o library

執行 dotnet sln 命令,將新建立的 library.csproj 專案新增至方案:Execute the dotnet sln command to add the newly created library.csproj project to the solution:

dotnet sln add library/library.csproj

library.csproj 檔案包含下列資訊:The library.csproj file contains the following information:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

</Project>

我們的程式庫方法會序列化及還原序列化 JSON 格式的物件。Our library methods serialize and deserialize objects in JSON format. 若要支援 JSON 序列化及還原序列化,請新增 Newtonsoft.Json NuGet 套件的參考。To support JSON serialization and deserialization, add a reference to the Newtonsoft.Json NuGet package. dotnet add 命令會新增項目至專案。The dotnet add command adds new items to a project. 若要新增 NuGet 套件的參考,請使用 dotnet add package 命令,並指定套件的名稱:To add a reference to a NuGet package, use the dotnet add package command and specify the name of the package:

dotnet add library package Newtonsoft.Json

這會將 Newtonsoft.Json 及其相依性新增至程式庫專案。This adds Newtonsoft.Json and its dependencies to the library project. 或者,手動編輯 library.csproj 檔案,並新增下列節點:Alternatively, manually edit the library.csproj file and add the following node:

<ItemGroup>
  <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>

執行 dotnet restore (請參閱注意事項),以還原相依性,並在其中有三個檔案的 library 內建立 obj 資料夾,包含 project.assets.json 檔案:Execute dotnet restore, (see note) which restores dependencies and creates an obj folder inside library with three files in it, including a project.assets.json file:

dotnet restore

library 資料夾中,將檔案 Class1.cs 重新命名為 Thing.csIn the library folder, rename the file Class1.cs to Thing.cs. 使用下列內容取代程式碼:Replace the code with the following:

using static Newtonsoft.Json.JsonConvert;

namespace Library
{
    public class Thing
    {
        public int Get(int left, int right) =>
            DeserializeObject<int>($"{left + right}");
    }
}

Thing 類別包含一個公用方法 Get,這個公用方法會傳回兩個數字的總和,而做法是將總和轉換成字串,然後將它還原序列化為整數。The Thing class contains one public method, Get, which returns the sum of two numbers but does so by converting the sum into a string and then deserializing it into an integer. 這會利用一些現代 C# 功能,例如 using static指示詞運算式主體成員字串內插補點This makes use of a number of modern C# features, such as using static directives, expression-bodied members, and string interpolation.

使用 dotnet build 命令建置程式庫。Build the library with the dotnet build command. 這會在 golden/library/bin/Debug/netstandard1.4 底下產生 library.dll 檔案:This produces a library.dll file under golden/library/bin/Debug/netstandard1.4:

dotnet build

建立測試專案Create the test project

建置程式庫的測試專案。Build a test project for the library. golden 資料夾中,建立新的測試專案︰From the golden folder, create a new test project:

dotnet new xunit -o test-library

將測試專案新增至方案:Add the test project to the solution:

dotnet sln add test-library/test-library.csproj

新增上一節中所建立之程式碼的專案參考,讓編譯器可以尋找及使用程式庫專案。Add a project reference the library you created in the previous section so that the compiler can find and use the library project. 使用 dotnet add reference 命令:Use the dotnet add reference command:

dotnet add test-library/test-library.csproj reference library/library.csproj

或者,手動編輯 test-library.csproj 檔案,並新增下列節點:Alternatively, manually edit the test-library.csproj file and add the following node:

<ItemGroup>
  <ProjectReference Include="..\library\library.csproj" />
</ItemGroup>

既然已正確設定相依性,請建立您程式庫的測試。Now that the dependencies have been properly configured, create the tests for your library. 開啟 UnitTest1.cs 並將其內容取代為下列程式碼:Open UnitTest1.cs and replace its contents with the following code:

using Library;
using Xunit;

namespace TestApp
{
    public class LibraryTests
    {
        [Fact]
        public void TestThing() {
            Assert.NotEqual(42, new Thing().Get(19, 23));
        }
    }
}

請注意,當您第一次建立單元測試時,確認值 42 不等於 19+23 (或 42) (Assert.NotEqual),而這項建立作業會失敗。Note that you assert the value 42 is not equal to 19+23 (or 42) when you first create the unit test (Assert.NotEqual), which will fail. 建置單元測試的重要步驟是建立測試,以確認其邏輯在第一次時失敗一次。An important step in building unit tests is to create the test to fail once first to confirm its logic.

golden 資料夾中,執行下列命令:From the golden folder, execute the following commands:

dotnet restore 
dotnet test test-library/test-library.csproj

這些命令會以遞迴方式尋找所有專案來還原相依性、建置相依性,並啟動 xUnit 測試執行器來執行測試。These commands will recursively find all projects to restore dependencies, build them, and activate the xUnit test runner to run the tests. 如您所預期,單一測試失敗。The single test fails, as you expect.

編輯 UnitTest1.cs 檔案,並將判斷提示從 Assert.NotEqual 變更為 Assert.EqualEdit the UnitTest1.cs file and change the assertion from Assert.NotEqual to Assert.Equal. golden 資料夾中執行下列命令,以重新執行測試,而這次測試會通過:Execute the following command from the golden folder to re-run the test, which passes this time:

dotnet test test-library/test-library.csproj

建立主控台應用程式Create the console app

您透過下列步驟所建立的主控台應用程式依存於您先前建立的程式庫專案,並在它執行時呼叫它的程式庫方法。The console app you create over the following steps takes a dependency on the library project you created earlier and calls its library method when it runs. 使用這種模式的開發,您會看到如何建立多個專案的可重複使用程式庫。Using this pattern of development, you see how to create reusable libraries for multiple projects.

golden 資料夾中,建立新的主控台應用程式︰Create a new console application from the golden folder:

dotnet new console -o app

將主控台應用程式專案新增至方案:Add the console app project to the solution:

dotnet sln add app/app.csproj

執行 dotnet add reference 命令,建立與程式庫的相依性︰Create the dependency on the library by running the dotnet add reference command:

dotnet add app/app.csproj reference library/library.csproj

執行 dotnet restore (請參閱注意事項),還原方案中三個專案的相依性。Run dotnet restore (see note) to restore the dependencies of the three projects in the solution. 開啟 Program.cs,並將 Main 方法的內容取代為下行:Open Program.cs and replace the contents of the Main method with the following line:

WriteLine($"The answer is {new Thing().Get(19, 23)}");

將兩個 using 指示詞新增至 Program.cs 檔案的頂端:Add two using directives to the top of the Program.cs file:

using static System.Console;
using Library;

執行下列 dotnet run 命令來執行可執行檔,而 dotnet run-p 選項指定主要應用程式的專案。Execute the following dotnet run command to run the executable, where the -p option to dotnet run specifies the project for the main application. 應用程式會產生 "The answer is 42" 字串。The app produces the string "The answer is 42".

dotnet run -p app/app.csproj

進行應用程式偵錯Debug the application

Main 方法中的 WriteLine 陳述式設定中斷點。Set a breakpoint at the WriteLine statement in the Main method. 做法是在游標位於 WriteLine 行上方時按下 F9 鍵,或在您要設定中斷點之行的左邊界按一下滑鼠。Do this by either pressing the F9 key when the cursor is over the WriteLine line or by clicking the mouse in the left margin on the line where you want to set the breakpoint. 紅色圓圈會出現在程式碼行旁邊的邊界。A red circle will appear in the margin next to the line of code. 到達中斷點時,會在執行中斷點行「之前」停止執行程式碼。When the breakpoint is reached, code execution will stop before the breakpoint line is executed.

開啟偵錯工具索引標籤,方法是選取 Visual Studio Code 工具列中的偵錯圖示、選取功能表列中的 [檢視] > [偵錯],或使用鍵盤快速鍵 CTRL+SHIFT+DOpen the debugger tab by selecting the Debug icon in the Visual Studio Code toolbar, selecting View > Debug from the menu bar, or using the keyboard shortcut CTRL+SHIFT+D:

Visual Studio Code 偵錯工具

按下 [播放] 按鈕,在偵錯工具中啟動應用程式。Press the Play button to start the application under the debugger. 應用程式會開始執行,並執行至中斷點,然後停止。The app begins execution and runs to the breakpoint, where it stops. 逐步執行 Get 方法,並確定您已傳入正確的引數。Step into the Get method and make sure that you have passed in the correct arguments. 確認答案是 42。Confirm that the answer is 42.

注意

從 .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.