C#的System.CommandLine怎么使用

发布时间:2022-10-21 09:51:05 作者:iii
来源:亿速云 阅读:139

本篇内容主要讲解“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

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

到此,相信大家对“C#的System.CommandLine怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. c#集合的使用
  2. DatePicker的使用 C#

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

system.commandline

上一篇:如何用C# ftp检测目录是否存在和创建文件夹

下一篇:如何用C#代码实现将Html转为Word

相关阅读

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

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