快速入門:在 Visual Studio 中安裝並使用套件 (僅限 Windows)Quickstart: Install and use a package in Visual Studio (Windows only)

NuGet 套件包含可重複使用的程式碼,由其他開發人員提供您在專案中使用。NuGet packages contain reusable code that other developers make available to you for use in your projects. 請參閱什麼是 NuGet?了解背景知識。See What is NuGet? for background. 套件使用 NuGet 套件管理員或套件管理員主控台安裝到 Visual Studio 專案中。Packages are installed into a Visual Studio project using the NuGet Package Manager or the Package Manager Console. 此文章示範使用熱門的 Newtonsoft.Json (英文) 套件與 Windows Presentation Foundation (WPF) 專案的程序。This article demonstrates the process using the popular Newtonsoft.Json package and a Windows Presentation Foundation (WPF) project. 相同的程序適用於任何其他 .NET 或 .NET Core 專案。The same process applies to any other .NET or .NET Core project.

安裝之後,請使用 using <namespace> 參考程式碼中的套件,其中 <namespace> 為您使用的套件專用。Once installed, refer to the package in code with using <namespace> where <namespace> is specific to the package you're using. 建立參考之後,您可以透過其 API 呼叫套件。Once the reference is made, you can call the package through its API.

提示

從 nuget.org 開始:.NET 開發人員通常是透過瀏覽 nuget.org 來尋找可在自己應用程式中重複使用的元件。Start with nuget.org: Browsing nuget.org is how .NET developers typically find components they can reuse in their own applications. 您可以直接搜尋 nuget.org,或在 Visual Studio 中尋找並安裝套件,如此文章所示。You can search nuget.org directly or find and install packages within Visual Studio as shown in this article. 如需一般資訊,請參閱尋找和評估 NuGet 套件For general information, see Find and evaluate NuGet packages.

先決條件Prerequisites

  • 包含 .NET 桌面開發工作負載的 Visual Studio 2019。Visual Studio 2019 with the .NET Desktop Development workload.

您可以從 visualstudio.com 免費安裝 2019 Community Edition,或使用 Professional Edition 或 Enterprise Edition。You can install the 2019 Community edition for free from visualstudio.com or use the Professional or Enterprise editions.

如果您使用的是 Visual Studio for Mac,請參閱在專案中包含 NuGet 套件If you're using Visual Studio for Mac, see Include a NuGet package in your project.

建立專案Create a project

假設 NuGet 套件 支援與專案相同的目標架構,則該套件就可安裝到任何的 .NET 專案中。NuGet packages can be installed into any .NET project, provided that the package supports the same target framework as the project.

在此逐步解說中,請使用簡單的 WPF 應用程式。For this walkthrough, use a simple WPF app. 使用 [檔案] > [新增專案] 在 Visual Studio 中建立專案、在搜尋方塊中輸入 .NET,然後選取 [WPF 應用程式 (.NET Framework)] 。Create a project in Visual Studio using File > New Project..., typing .NET in the search box, and then selecting the WPF App (.NET Framework). 按一下 [下一步] 。Click Next. 出現提示時,接受 [架構] 的預設值。Accept the default values for Framework when prompted.

Visual Studio 隨即建立專案,而專案會在 [方案總管] 中開啟。Visual Studio creates the project, which opens in Solution Explorer.

新增 Newtonsoft.Json NuGet 套件Add the Newtonsoft.Json NuGet package

若要安裝套件,您可以使用 NuGet 套件管理員或套件管理員主控台。To install the package, you can use either the NuGet Package Manager or the Package Manager Console. 當您安裝套件時,NuGet 會在您的專案檔或 packages.config 檔案中 (視專案格式而定) 記錄相依性。When you install a package, NuGet records the dependency in either your project file or a packages.config file (depending on the project format). 如需詳細資訊,請參閱套件使用概觀和工作流程For more information, see Package consumption overview and workflow.

NuGet 封裝管理員NuGet Package Manager

  1. 在方案總管中以滑鼠右鍵按一下 [參考] ,選擇 [管理 NuGet 套件] 。In Solution Explorer, right-click References and choose Manage NuGet Packages.

    專案參考的管理 NuGet 套件命令

  2. 選擇 "nuget.org" 作為 [套件來源] ,選取 [瀏覽] 索引標籤、搜尋 [Newtonsoft.Json] 、在清單中選取該套件,然後選取 [安裝] :Choose "nuget.org" as the Package source, select the Browse tab, search for Newtonsoft.Json, select that package in the list, and select Install:

    尋找 Newtonsoft.Json 套件

    如果您需要 NuGet 套件管理員的詳細資訊,請參閱使用 Visual Studio 安裝及管理套件If you want more information on the NuGet Package Manager, see Install and manage packages using Visual Studio.

  3. 接受任何授權提示。Accept any license prompts.

  4. (僅限 Visual Studio 2017) 如果系統提示您選取套件管理格式,請選取 [專案檔中的 PackageReference] :(Visual Studio 2017 only) If prompted to select a package management format, select PackageReference in project file:

    選取套件管理格式

  5. 如果提示您檢閱變更,請選取 [確定] 。If prompted to review changes, select OK.

套件管理員主控台Package Manager Console

  1. 選取 [工具] > [NuGet 套件管理員] > [套件管理員主控台] 功能表命令。Select the Tools > NuGet Package Manager > Package Manager Console menu command.

  2. 在主控台開啟之後,檢查 [預設專案] 下拉式清單是否顯示您要安裝套件的專案。Once the console opens, check that the Default project drop-down list shows the project into which you want to install the package. 如果您在方案中只有一個專案,則已經選取該專案。If you have a single project in the solution, it is already selected.

    尋找 Newtonsoft.Json 套件

  3. 輸入命令 Install-Package Newtonsoft.Json (請參閱 Install-Package)。Enter the command Install-Package Newtonsoft.Json (see Install-Package). 主控台視窗會顯示命令的輸出。The console window shows output for the command. 錯誤通常會指出套件與專案的目標 Framework 不相容。Errors typically indicate that the package isn't compatible with the project's target framework.

    如果您需要套件管理員主控台的詳細資訊,請參閱使用套件管理員主控台安裝及管理套件If you want more information on the Package Manager Console, see Install and manage packages using Package Manager Console.

在應用程式中使用 Newtonsoft.Json APIUse the Newtonsoft.Json API in the app

在專案中使用 Newtonsoft.Json 套件,您可以呼叫其 JsonConvert.SerializeObject 方法,將物件轉換成人類可閱讀的字串。With the Newtonsoft.Json package in the project, you can call its JsonConvert.SerializeObject method to convert an object to a human-readable string.

  1. 開啟 MainWindow.xaml 並使用下列內容取代現有的 Grid 元素:Open MainWindow.xaml and replace the existing Grid element with the following:

    <Grid Background="White">
        <StackPanel VerticalAlignment="Center">
            <Button Click="Button_Click" Width="100px" HorizontalAlignment="Center" Content="Click Me" Margin="10"/>
            <TextBlock Name="TextBlock" HorizontalAlignment="Center" Text="TextBlock" Margin="10"/>
        </StackPanel>
    </Grid>
    
  2. 開啟 MainWindow.xaml.cs 檔案 (位於方案總管的 MainWindow.xaml 節點下方),然後將下列程式碼插入 MainWindow 類別內:Open the MainWindow.xaml.cs file (located in Solution Explorer under the MainWindow.xaml node), and insert the following code inside the MainWindow class:

    public class Account
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime DOB { get; set; }
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Account account = new Account
        {
            Name = "John Doe",
            Email = "john@microsoft.com",
            DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
        };
        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
        TextBlock.Text = json;
    }
    
  3. 即使在專案中新增了 Newtonsoft.Json 套件,JsonConvert 下方還是會出現紅色波浪線,因為您需要在程式碼檔案頂端使用 using 陳述式:Even though you added the Newtonsoft.Json package to the project, red squiggles appears under JsonConvert because you need a using statement at the top of the code file:

    using Newtonsoft.Json;
    
  4. 按 F5 或選取 [偵錯] > [開始偵錯] ,來建置並執行應用程式:Build and run the app by pressing F5 or selecting Debug > Start Debugging:

    WPF 應用程式的初始輸出

  5. 選取按鈕以查看使用一些 JSON 文字取代的 TextBlock 內容:Select on the button to see the contents of the TextBlock replaced with some JSON text:

    選取按鈕之後的 WPF 應用程式輸出

後續步驟Next steps

恭喜,您安裝並使用了您的第一個 NuGet 套件!Congratulations on installing and using your first NuGet package!

若要深入探索 NuGet 所提供的功能,請選取下列連結。To explore more that NuGet has to offer, select the links below.