zoukankan      html  css  js  c++  java
  • 通过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虽然也支持像传统命令行的库那样编写复杂的命令行支持程序,但这不在本文的介绍范围内。感兴趣的朋友可以看一下参考文章的内容。

    参考文章:

  • 相关阅读:
    ubuntu nfs server config
    增加虚拟机ubuntu的硬盘
    MD5算法
    MySQL错误ERROR 1366 (HY000): Incorrect string value..
    SQLPro Studio链接本地MYSQL
    mysql修改root密码
    jdk7 for Mac
    mysql is stop 点击start启动不了,卸载重装
    Mac版Intellij IDEA弹窗报this license XXXXXXXX has been cancelled
    Python 环境搭建
  • 原文地址:https://www.cnblogs.com/TianFang/p/10618573.html
Copyright © 2011-2022 走看看