c# - System.CommandLine 解析的值与输入不匹配

标签 c# system.commandline

我正在尝试使用 System.CommandLine,但无法让我的处理程序查看我传入的任何值。我尝试了最简单的命令行程序只是为了查看是否有任何值成功了,但到目前为止我还没有成功。我的目标是 .NET 4.7.2,并且使用 System.CommandLine 2.0.0-beta1.20574.7

    using System;
    using System.CommandLine;
    using System.CommandLine.Invocation;

    static class Program
    {
        public static void Main(string[] args)
        {
            var rootCommand = new RootCommand
            {
                new Option("--continue", "continue option")
            };

            rootCommand.Description = "Testing System.CommandLine";

            rootCommand.Handler = CommandHandler.Create<bool>
                ((willContinue) => run(willContinue));

            rootCommand.Invoke(args);
        }

        private static void run(bool willContinue)
        {
            Console.WriteLine(willContinue);
        }
    }

无论我如何调用我的应用程序,我都没有看到 willContinue 的值(value)是真实的。

myapp.exe --继续 -> False

myapp.exe --cont -> 无法识别的命令或参数“--cont”(我的选项至少被识别)

myapp.exe --Continue true -> 无法识别的命令或参数“true”

myapp.exe --help ->

myapp:
Testing System.CommandLine

Usage:
myapp [options]

Options:
--continue continue option
--version Show version information
-?, -h, --help Show help and usage information

最佳答案

您需要解决两件事:

  1. 添加选项类型,为bool
  2. 更改选项名称以匹配参数名称

以下命令有效:

var rootCommand = new RootCommand
{
    new Option<bool>("--willContinue", "continue option")
};

并这样调用它

myapp.exe --willContinue true

选项名称和参数名称并不总是必须匹配,但在这种情况下它不起作用,因为“继续”是保留字

关于c# - System.CommandLine 解析的值与输入不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66035905/

相关文章:

c# - 在 Silverlight 中创建倒计时器

javascript - 使用 Gulp 在 .less 更改上构建 csproj

c# - 无法访问 GridViewColumn 的内容中的事件

c# - 如何使用 XmlSerializer 将异构子节点反序列化为一个集合?

c# - 如何判断在使用 System.CommandLine 时是否指定了一个选项?

c# - 使用具有自定义 Main() 签名的 System.CommandLine

c# - 在嵌套异步方法中使用 ConfigureAwait