經過System.CommandLine快速生成支持命令行的應用

一直以來,當咱們想讓咱們的控制檯程序支持命令行啓動時,每每須要編寫大量代碼來實現這一看起來很簡單的功能。雖然有一些庫能夠簡化一些操做,但整個過程仍然是一個至關枯燥而乏味的過程。我以前也寫過一些文章簡單的介紹過它們:html

今天,我這裏要介紹一個新的命令行庫:System.CommandLine,經過他咱們能夠幾乎無需任何額外的編碼就能夠得到命令行的支持,它能大幅減小程序員花在提供命令行API(CLI)上的時間,改善CLI程序用戶的體驗,讓開發者能專一於編寫應用程序。git

目前這個庫仍是預覽版本,要體驗的話須要可使用以下庫:System.CommandLine.DragonFruit。首先以一個簡單的示例來演示它的功能。程序員

static void Main(string input, string output)
{
    Console.WriteLine($"Input: {input}, Output: {output}");
}

這裏咱們並無要顯式使用這個庫,只須要將Main函數的入參改爲咱們須要使用的類型,程序便自動實現了命令行的支持。咱們甚至能夠用—help查看程序的命令行的配置方式github

    ConsoleApp1.exe --help
    Usage:
     ConsoleApp1 [options]
    Options:
     --input <INPUT> input
     --output <OUTPUT> output
     --version Display version information
api

可見,它能自動根據Main函數的參數自動解析出命令行的格式,並生成幫助文檔。 函數

接着,咱們再來看看命令行的使用: ui

    ConsoleApp1 --input ii --output out
    Input: ii, Output: out
編碼

完美的進行了命令行的解析,它也能夠讀取xml註釋,實現更加複雜的說明。spa

/// <summary>
/// Converts an image file from one format to another.
/// </summary>
/// <param name="input">The path to the image file that is to be converted.</param>
/// <param name="output">The name of the output from the conversion.</param>
/// <param name="xCropSize">The x dimension size to crop the picture. The default is 0 indicating no cropping is required.</param>
/// <param name="yCropSize">The x dimension size to crop the picture. The default is 0 indicating no cropping is required.</param>
static void Main(string input, string output, int xCropSize = 0, int yCropSize = 0)
{
}

生成的幫助輸出效果以下:.net

    ConsoleApp1:
     Converts an image file from one format to another.
    Usage:
     ConsoleApp1 [options]
    Options:
     --input <INPUT> The path to the image file that is to be converted.
     --output <OUTPUT> The name of the output from the conversion.
     --x-crop-size <X-CROP-SIZE> The x dimension size to crop the picture. The default is 0 indicating no cropping is required.
     --y-crop-size <Y-CROP-SIZE> The x dimension size to crop the picture. The default is 0 indicating no cropping is required.
     --version Display version information

 相比傳統的命令行庫,這個庫的優點很是明顯,咱們能夠幾乎不編寫任何代碼就能夠得到命令行程序的支持。對於複雜的命令行程序來講,可能這裏的方式並不能知足需求。System.CommandLine雖然也支持像傳統命令行的庫那樣編寫複雜的命令行支持程序,但這不在本文的介紹範圍內。感興趣的朋友能夠看一下參考文章的內容。

參考文章:

相關文章
相關標籤/搜索