一直以来,当咱们想让咱们的控制台程序支持命令行启动时,每每须要编写大量代码来实现这一看起来很简单的功能。虽然有一些库能够简化一些操做,但整个过程仍然是一个至关枯燥而乏味的过程。我以前也写过一些文章简单的介绍过它们: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虽然也支持像传统命令行的库那样编写复杂的命令行支持程序,但这不在本文的介绍范围内。感兴趣的朋友能够看一下参考文章的内容。
参考文章: