C#通過System.CommandLine快速生成支持命令行的應(yīng)用程序
一直以來,當(dāng)我們想讓我們的控制臺程序支持命令行啟動時(shí),往往需要編寫大量代碼來實(shí)現(xiàn)這一看起來很簡單的功能。雖然有一些庫可以簡化一些操作,但整個(gè)過程仍然是一個(gè)相當(dāng)枯燥而乏味的過程。
今天,我這里要介紹一個(gè)新的命令行庫:System.CommandLine,通過他我們可以幾乎無需任何額外的編碼就可以獲得命令行的支持,它能大幅減少程序員花在提供命令行API(CLI)上的時(shí)間,改善CLI程序用戶的體驗(yàn),讓開發(fā)者能專注于編寫應(yīng)用程序。
目前這個(gè)庫還是預(yù)覽版本,要體驗(yàn)的話需要可以使用如下庫:System.CommandLine.DragonFruit。首先以一個(gè)簡單的示例來演示它的功能。
static void Main(string input, string output) { Console.WriteLine($"Input: {input}, Output: {output}"); }
這里我們并沒有要顯式使用這個(gè)庫,只需要將Main函數(shù)的入?yún)⒏某晌覀冃枰褂玫念愋?,程序便自動?shí)現(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
完美的進(jìn)行了命令行的解析,它也可以讀取xml注釋,實(shí)現(xiàn)更加復(fù)雜的說明。
/// <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)的命令行庫,這個(gè)庫的優(yōu)勢非常明顯,我們可以幾乎不編寫任何代碼就可以獲得命令行程序的支持。對于復(fù)雜的命令行程序來說,可能這里的方式并不能滿足需求。System.CommandLine雖然也支持像傳統(tǒng)命令行的庫那樣編寫復(fù)雜的命令行支持程序,但這不在本文的介紹范圍內(nèi)。感興趣的朋友可以看一下參考文章的內(nèi)容。
參考文章:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#?Timer控件學(xué)習(xí)之使用Timer解決按鈕冪等性問題
Timer控件又稱定時(shí)器控件或計(jì)時(shí)器控件,該控件的主要作用是按一定的時(shí)間間隔周期性地觸發(fā)一個(gè)名為Tick的事件,因此在該事件的代碼中可以放置一些需要每隔一段時(shí)間重復(fù)執(zhí)行的程序段,這篇文章主要介紹了關(guān)于C#使用Timer解決按鈕冪等性問題的相關(guān)資料,需要的朋友可以參考下2022-10-10在C# WPF下自定義滾動條ScrollViewer樣式的操作
這篇文章主要介紹了在C# WPF下自定義滾動條ScrollViewer樣式的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01C#數(shù)據(jù)庫操作類AccessHelper實(shí)例
這篇文章主要介紹了C#數(shù)據(jù)庫操作類AccessHelper實(shí)例,可實(shí)現(xiàn)針對access數(shù)據(jù)庫的各種常見操作,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-10-10