下面的简单Program.cs要求已定义的根命令只有一个参数:

using System.CommandLine;

var inputArgument = new Argument<string>(
  name: "--input", 
  description: "input any value and print it out");

var rootCommand = new RootCommand();
rootCommand.AddArgument(inputArgument);
rootCommand.SetHandler((inputArgumentValue) =>
{
  Console.WriteLine($"{inputArgumentValue}");
}, inputArgument);

rootCommand.Invoke(args);

我希望使用以下参数调用它:--input "Hello World"以在shell 中打印出Hello World.但是,我得到以下错误:

Unrecognized command or argument 'Hello World'.

当我将Argument类替换为Option类时,它按预期工作:

using System.CommandLine;

var inputArgument = new Option<string>(
  name: "--input", 
  description: "input any value and print it out");

var rootCommand = new RootCommand();
rootCommand.AddOption(inputArgument);
rootCommand.SetHandler((inputArgumentValue) =>
{
  Console.WriteLine($"{inputArgumentValue}");
}, inputArgument);

rootCommand.Invoke(args);

What did I misunderstand about the 100 class? Why can I not pass an argument with a value to it?


由于它的其他属性,我想使用参数类而不是选项.我使用的是.NET 6.0和System.CommandLine版本2.0.0-beta4.22272.1

推荐答案

看看这Command-line syntax overview for System.CommandLine份文档吧.

它将options定义为:

选项是可以传递给命令的命名参数.POSIX约定是在选项名前面加上两个连字符(--).

arguments作为:

参数是传递给选项或命令的值.

因此,基本上参数是传递给命令或选项的无名位置参数,也就是说,对于您的第一个代码段,有效调用将是:

appName "Hello World"

当然,您可以添加两个参数:

var inputArgument = new Argument<string>(
    name: "input", 
    description: "input any value and print it out");
var inputArgument2 = new Argument<string>(
    name: "input2", 
    description: "input any value and print it out");

var rootCommand = new RootCommand();
rootCommand.AddArgument(inputArgument);
rootCommand.AddArgument(inputArgument2);
rootCommand.SetHandler((inputArgumentValue, inputArgumentValue2) =>
{
    Console.WriteLine($"{inputArgumentValue} - {inputArgumentValue2}");
}, inputArgument, inputArgument2);

然后,您的appName --input "Hello World"调用将导致处理程序为inputArgumentValue获得2个值--input,为inputArgumentValue2获得"Hello World"个值.

但我认为使用Option<string>(第二个代码片段)应该是更正确的方法(它还允许传递以=:appName --input="Hello World"分隔的值).

Csharp相关问答推荐

Blazor:计算值或保留为默认值

ListaryImportProperty的默认DllImportSearchPathsProperty行为

通过条件列表删除/更新EF Core 7中的实体的有效方法

Unity中的刚体2D运动

如何注册实现同一接口的多个服务并注入到控制器构造函数中

Azure Function应用(. NET 8)不将信息记录到应用洞察

.NET 6控制台应用程序,RabbitMQ消费不工作时,它的程序文件中的S

如何在Windows 11任务调度程序中每1分钟重复一次任务?

StackExchange.Redis.RedisServerException:调用ITransaction.ExecuteAsync()时出现错误未知命令取消监视

在.NET MAUI.NET 8中如何防止按钮点击时出现灰色反馈

如何注册类使用多级继承与接口

在swagger示例中添加默认数组列表

HttpClient SendAsync与多线程环境中的ArchiveZip

记录类型';==运算符是否与实现IEquatable<;T&>;的类中的';equals&>方法执行等价比较?

如何在onNext之前等待订阅者完成?

使用switch 类型模式时出现奇怪的编译器行为

如何从另一个类的列表中按ID取值

使用ASP.NET MVC for Lemon Squeezy X-Signature创建散列

使DefaultIfEmpty返回空

.NET6最小API:操作.MapGet之后的响应