C#怎么通过System.CommandLine快速生成支持命令行的应用程序

发布时间:2022-07-13 14:22:46 作者:iii
来源:亿速云 阅读:163

这篇文章主要介绍了C#怎么通过System.CommandLine快速生成支持命令行的应用程序的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇C#怎么通过System.CommandLine快速生成支持命令行的应用程序文章都会有所收获,下面我们一起来看看吧。

一直以来,当我们想让我们的控制台程序支持命令行启动时,往往需要编写大量代码来实现这一看起来很简单的功能。虽然有一些库可以简化一些操作,但整个过程仍然是一个相当枯燥而乏味的过程。

今天,我这里要介绍一个新的命令行库:System.CommandLine,通过他我们可以几乎无需任何额外的编码就可以获得命令行的支持,它能大幅减少程序员花在提供命令行API(CLI)上的时间,改善CLI程序用户的体验,让开发者能专注于编写应用程序。

目前这个库还是预览版本,要体验的话需要可以使用如下库:System.CommandLine.DragonFruit。首先以一个简单的示例来演示它的功能。

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

这里我们并没有要显式使用这个库,只需要将Main函数的入参改成我们需要使用的类型,程序便自动实现了命令行的支持。我们甚至可以用—help查看程序的命令行的配置方式

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

可见,它能自动根据Main函数的参数自动解析出命令行的格式,并生成帮助文档。

接着,我们再来看看命令行的使用:

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

完美的进行了命令行的解析,它也可以读取xml注释,实现更加复杂的说明。

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

相比传统的命令行库,这个库的优势非常明显,我们可以几乎不编写任何代码就可以获得命令行程序的支持。对于复杂的命令行程序来说,可能这里的方式并不能满足需求。

关于“C#怎么通过System.CommandLine快速生成支持命令行的应用程序”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C#怎么通过System.CommandLine快速生成支持命令行的应用程序”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 快速生成网站
  2. C# 获取应用程序的路径

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

system.commandline

上一篇:js数组去重怎么实现

下一篇:怎么使用高斯Redis实现二级索引

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》