写在前面

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

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

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

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

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

需要说明的是由于项目还是处于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

调用结果

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

12-18 11:11