日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C#通過System.CommandLine快速生成支持命令行的應用程序_C#教程

作者:天方 ? 更新時間: 2022-09-01 編程語言

一直以來,當我們想讓我們的控制臺程序支持命令行啟動時,往往需要編寫大量代碼來實現(xiàn)這一看起來很簡單的功能。雖然有一些庫可以簡化一些操作,但整個過程仍然是一個相當枯燥而乏味的過程。

今天,我這里要介紹一個新的命令行庫:System.CommandLine,通過他我們可以幾乎無需任何額外的編碼就可以獲得命令行的支持,它能大幅減少程序員花在提供命令行API(CLI)上的時間,改善CLI程序用戶的體驗,讓開發(fā)者能專注于編寫應用程序。

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

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

這里我們并沒有要顯式使用這個庫,只需要將Main函數(shù)的入?yún)⒏某晌覀冃枰褂玫念愋停绦虮阕詣訉崿F(xiàn)了命令行的支持。我們甚至可以用—help查看程序的命令行的配置方式

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

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

接著,我們再來看看命令行的使用:

????ConsoleApp1 --input ii --output out
????Input: ii, Output: out

完美的進行了命令行的解析,它也可以讀取xml注釋,實現(xiàn)更加復雜的說明。

/// <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)
{
}

生成的幫助輸出效果如下:

????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

相比傳統(tǒng)的命令行庫,這個庫的優(yōu)勢非常明顯,我們可以幾乎不編寫任何代碼就可以獲得命令行程序的支持。對于復雜的命令行程序來說,可能這里的方式并不能滿足需求。System.CommandLine雖然也支持像傳統(tǒng)命令行的庫那樣編寫復雜的命令行支持程序,但這不在本文的介紹范圍內(nèi)。感興趣的朋友可以看一下參考文章的內(nèi)容。

參考文章:

  • 使用 System.CommandLine 分析命令行

  • command-line-api

原文鏈接:https://www.cnblogs.com/TianFang/p/10618573.html

欄目分類
最近更新