Skip to content
This repository was archived by the owner on Mar 6, 2025. It is now read-only.

Latest commit

 

History

History
122 lines (88 loc) · 4.32 KB

File metadata and controls

122 lines (88 loc) · 4.32 KB
title 使用 dotnet CLI 安装并使用 NuGet 包
description 有关如何在 .NET Core 项目中安装并使用 NuGet 包的演练教程。
author karann-msft
ms.author karann
ms.date 01/23/2018
ms.topic quickstart
ms.openlocfilehash 006fff8360ac62393e4b88c1a253514591d22f4c
ms.sourcegitcommit 2b50c450cca521681a384aa466ab666679a40213
ms.translationtype HT
ms.contentlocale zh-CN
ms.lasthandoff 04/07/2020
ms.locfileid 78231265

快速入门:使用 dotnet CLI 安装并使用包

NuGet 包包含其他开发人员提供的在项目中使用的可重用代码。 请参阅什么是 NuGet?,了解背景信息。 使用如本文所述的适用于常用 Newtonsoft.Json 包的 dotnet add package 命令将包安装到 .NET Core 项目中。

安装完成后,请引用具有 using <namespace> 的代码中的包,其中 <namespace> 特定于正在使用的包。 然后,可以使用包的 API。

Tip

nuget.org 入门:浏览 nuget.org 是 .NET 开发人员通常在自己的应用程序中查找可重用组件的方式。 你可以直接搜索 nuget.org 或根据本文中的介绍,在 Visual Studio 中查找和安装包。

必备条件

  • .NET Core SDK,提供 dotnet 命令行工具。 从 Visual Studio 2017 开始,dotnet CLI 将自动随任何与 .NET Core 相关的工作负载一起安装。

创建一个项目

可以将 NuGet 包安装到某种类型的 .NET 项目。 在本演练中,如下所示创建一个简单的 .NET Core 控制台项目:

  1. 为项目创建文件夹。

  2. 打开命令提示符并切换到新文件夹。

  3. 请使用以下命令创建项目:

    dotnet new console
    
  4. 使用 dotnet run 来测试已正确创建的应用。

添加 Newtonsoft.Json Nuget 包

  1. 运行以下命令安装 Newtonsoft.json 包:

    dotnet add package Newtonsoft.Json
    
  2. 该命令完成后,打开 .csproj 文件以查看所添加的引用:

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

在应用中使用 Newtonsoft.Json API

  1. 打开 Program.cs 文件,然后在文件的顶部添加以下行:

    using Newtonsoft.Json;
  2. class Program 行的前面添加以下代码:

    public class Account
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }
  3. 使用以下代码替换 Main 函数:

    static void Main(string[] args)
    {
        Account account = new Account
        {
            Name = "John Doe",
            Email = "[email protected]",
            DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
        };
    
        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
        Console.WriteLine(json);
    }
  4. 使用 dotnet run 命令生成并运行应用。 输出应是 Account 对象在代码中的 JSON 表示形式:

    {
      "Name": "John Doe",
      "Email": "[email protected]",
      "DOB": "1980-02-20T00:00:00Z"
    }
    

相关视频

[!Video https://channel9.msdn.com/Series/NuGet-101/Install-and-Use-a-NuGet-Package-with-the-NET-CLI-3-of-5/player]

第 9 频道YouTube 上查找更多 NuGet 视频。

后续步骤

祝贺你安装并使用第一个 NuGet 包!

[!div class="nextstepaction"] 使用 dotnet CLI 安装并使用包

若要了解更多 NuGet 产品,请选择以下链接。