C# 命令行参数解析库示例

写在前面

在日常开发中,我们经常会用到命令行参数,比如cmd下的各种指令;还有C#的控制台类型的项目,在默认入口Main函数中,那个args参数,就是有系统传入到程序进程的命令行参数;在传入的参数相对简单的情况下,默认的字符串数组还是够用的,但是如果需要构建更复杂的命令行参数时,通过字符串数组来实现就很麻烦了,特别是要实现类似 Linux 系统中的那种结构化指令,如下列所示:

iptables -I INPUT -p tcp --dport 9090 -j ACCEPT 

在C#的技术栈中可以使用System.CommandLine这个专门的命令行参数解析库来实现。

老规矩通过NuGet获取该类库:

需要说明的是由于项目还是处于beta状态,所以要把包括预发型版选项勾起来才能找到。

代码实现

using System.CommandLine;

class Program
{
    static async Task Main(string[] args)
    {
        var delayOption = new Option<int>
          (name: "--delay",
          description: "An option whose argument is parsed as an int.",
          getDefaultValue: () => 42);
        var messageOption = new Option<string>
            ("--message", "An option whose argument is parsed as a string.");

        var rootCommand = new RootCommand();
        rootCommand.Add(delayOption);
        rootCommand.Add(messageOption);

        rootCommand.SetHandler((delayOptionValue, messageOptionValue) =>
        {
            Console.WriteLine($"--delay = {delayOptionValue}");
            Console.WriteLine($"--message = {messageOptionValue}");
        },
            delayOption, messageOption);
        await rootCommand.InvokeAsync(args);
    }
}

这是微软官方做的一个示例代码,给它撸过来验证一下,关于命令行参数涉及到的具体概念,可以去官方项目做进一步了解。

GitHub - dotnet/command-line-api: Command line parsing, invocation, and rendering of terminal output.

How to define commands in System.CommandLine - .NET | Microsoft Learn

调用结果

相关推荐

  1. Python 命令参数解析 docopt

    2023-12-18 07:28:04       37 阅读
  2. C语言】命令参数

    2023-12-18 07:28:04       33 阅读
  3. Rust 命令参数解析指南

    2023-12-18 07:28:04       28 阅读
  4. rust clap命令解析

    2023-12-18 07:28:04       33 阅读
  5. flink源码分析 - 简单解析命令参数

    2023-12-18 07:28:04       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-18 07:28:04       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-18 07:28:04       97 阅读
  3. 在Django里面运行非项目文件

    2023-12-18 07:28:04       78 阅读
  4. Python语言-面向对象

    2023-12-18 07:28:04       88 阅读

热门阅读

  1. C# 内存的分配管理

    2023-12-18 07:28:04       56 阅读
  2. React 表单与事件

    2023-12-18 07:28:04       54 阅读
  3. 第二十章 : Spring Boot 集成RabbitMQ(四)

    2023-12-18 07:28:04       61 阅读
  4. 解决spa页面首屏加载慢的方式笔记

    2023-12-18 07:28:04       63 阅读
  5. 解决阿里云ECS磁盘在线扩容不生效

    2023-12-18 07:28:04       60 阅读
  6. 微服务Redis-Session共享登录状态

    2023-12-18 07:28:04       40 阅读
  7. centos-静态ip及修改主机名

    2023-12-18 07:28:04       55 阅读
  8. 【React基础三】组件传值、高阶组件、Hook

    2023-12-18 07:28:04       57 阅读
  9. 如何使用ffmpeg高效的压缩视频

    2023-12-18 07:28:04       62 阅读
  10. C语言学习day09:运算符(下)

    2023-12-18 07:28:04       61 阅读
  11. 【Vue3练习】Vue3使用v-model以及多个v-model

    2023-12-18 07:28:04       55 阅读
  12. vue模板语法

    2023-12-18 07:28:04       63 阅读
  13. 数据结构 | 二叉树的遍历(递归&非递归)

    2023-12-18 07:28:04       56 阅读
  14. 【NeurIPS 2023】多模态联合视频生成大模型CoDi

    2023-12-18 07:28:04       65 阅读