教程:使用 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 SDKInstall 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 CodeInstall 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,并按 Fn+F1 打开 Visual Studio Code 面板,从而安装 Visual Studio Code C# 扩展。Install the Visual Studio Code C# extension by opening Visual Studio Code and pressing Fn+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 Basic 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 article 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 > Terminal from the menu to open an embedded terminal in Visual Studio Code. 若要在 Visual Studio Code 外部执行操作,仍可以使用资源管理器的“通过命令提示符打开” (在 Mac 或 Linux 上,为“在终端中打开” )命令打开外部 shell。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 命令以在名为 golden 的新文件夹中创建新的解决方案 golden.sln :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

导航到新的 golden 文件夹,执行下列命令来创建库项目,它将在库 文件夹中生成 library.csproj 和 Class1.cs 这两个文件:Navigate 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请参阅注释),这将还原依赖项,并在库 中创建 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

在库 文件夹中,将文件 Class1.cs 重命名为 Thing.cs 。In 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 指令expression-bodied 成员字符串内插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));
        }
    }
}

请注意,在首次创建单元测试 (Assert.NotEqual) 时,已断言值 42 不等于 19+23(或 42),因此测试将失败。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. 在 goldden 文件夹中执行下列命令,重新运行测试,此次测试通过: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)}");

在 Program.cs 文件顶部添加两个 using 指令: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 行之上时按 Fn+F9 键,也可在想要设置断点的行的左侧边缘中单击鼠标。Do this by either pressing the Fn+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 工具栏中选择“调试”图标,再从菜单栏中依次选择“视图”>“调试” ,或使用键盘快捷方式 Command+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 Command+SHIFT+D:

Visual Studio Code 调试程序

按“开始”按钮,在调试器下启动应用程序。Press the Play button to start the application under the debugger. 你已在此项目中创建了测试项目和应用程序。You've created both a test project and an application in this project. 调试器会询问你要启动哪个项目。The debugger asks which project you want to start. 选择“应用”项目。Select the "app" project. 应用开始执行,运行到断点处停止。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 runStarting 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.