C#通過System.CommandLine快速生成支持命令行的應用程序
一直以來,當我們想讓我們的控制臺程序支持命令行啟動時,往往需要編寫大量代碼來實現(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)⒏某晌覀冃枰褂玫念愋?,程序便自動實現(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)容。
參考文章:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在C# WPF下自定義滾動條ScrollViewer樣式的操作
這篇文章主要介紹了在C# WPF下自定義滾動條ScrollViewer樣式的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01C#數(shù)據(jù)庫操作類AccessHelper實例
這篇文章主要介紹了C#數(shù)據(jù)庫操作類AccessHelper實例,可實現(xiàn)針對access數(shù)據(jù)庫的各種常見操作,非常具有實用價值,需要的朋友可以參考下2014-10-10