」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > C# |使用 System.CommandLine 庫建立命令列 (CLI) 應用程式

C# |使用 System.CommandLine 庫建立命令列 (CLI) 應用程式

發佈於2024-07-31
瀏覽:862

C# | Building a Command-Line (CLI) App using System.CommandLine Library

筆記
您可以查看我個人網站上的其他帖子:https://hbolajraf.net

介紹

在本指南中,我們將探討如何使用 C# 和 .NET 中的 System.CommandLine 程式庫建立命令列介面 (CLI) 應用程式。 System.CommandLine 簡化了為您的應用程式建立強大且功能豐富的命令列介面的過程。

先決條件

開始前,請確保您已安裝以下軟體:

  • .NET SDK(版本5.0或更高版本)

第 1 步:建立一個新的控制台應用程式

dotnet new console -n MyCommandLineApp
cd MyCommandLineApp

步驟2:新增System.CommandLine NuGet包

dotnet add package System.CommandLine --version 2.0.0-beta1.21308.1

步驟 3:定義命令列選項

在您的 Program.cs 中,使用 System.CommandLine 定義命令列選項:

using System.CommandLine;
using System.CommandLine.Invocation;

class Program
{
    static int Main(string[] args)
    {
        var rootCommand = new RootCommand
        {
            new Option("--number", "An integer option"),
            new Option("--flag", "A boolean option"),
            new Argument("input", "A required input argument")
        };

        rootCommand.Handler = CommandHandler.Create((number, flag, input) =>
        {
            // Your application logic goes here
            Console.WriteLine($"Number: {number}");
            Console.WriteLine($"Flag: {flag}");
            Console.WriteLine($"Input: {input}");
        });

        return rootCommand.Invoke(args);
    }
}

第 4 步:運行 CLI 應用程式

dotnet run -- --number 42 --flag true "Hello, CLI!"

將這些值替換為您自己的值並查看輸出。

第 5 步:自訂幫助文本

為您的選項和參數添加描述以獲得更好的幫助文字:

var rootCommand = new RootCommand
{
    new Option("--number", "An integer option"),
    new Option("--flag", "A boolean option"),
    new Argument("input", "A required input argument")
};

rootCommand.Description = "A simple CLI app";
rootCommand.Handler = CommandHandler.Create((number, flag, input) =>
{
    Console.WriteLine($"Number: {number}");
    Console.WriteLine($"Flag: {flag}");
    Console.WriteLine($"Input: {input}");
});

接下來是什麼?

您已使用 C# 和 .NET 中的 System.CommandLine 程式庫成功建立了基本的命令列介面 (CLI) 應用程式。根據您的具體要求自訂和擴展應用程式。
更多資訊請參考官方文件:System.CommandLine GitHub

版本聲明 本文轉載於:https://dev.to/hbolajraf/c-building-a-command-line-cli-app-using-systemcommandline-library-128e如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3