C# - 控制台应用程序 - 如何读取CLI选项参数

发布于 2025-01-25 18:47:13 字数 860 浏览 3 评论 0原文

使用system.commandline v.2.0.0-beta3.22114.1system.commandline.commandline.namingconconcenventionbinder v.2.0.0.0.0.0.22114.1,我正在尝试创建创建一个简单的get命令,带有- 名称选项。

需要该选项。它期望一个参数,并且将在console.writeline语句中使用它。

为了组织,我正在单独的类文件中创建命令,并继承命令类。

public class GetCommand : Command
{
    public GetCommand()
        :base("get", "Filters events by name.")
    {
        var name = new Option("--name", "The name of the event you like to fetch.")
        {
            IsRequired = true,
        };

        AddOption(name);
        Handler = CommandHandler.Create((string name) => Console.WriteLine(name));

        
    }
}

在运行应用程序时,当我使用get -name ali命令,选项和参数运行可执行文件时,我一直在获得以下例外: 未识别的命令或参数'ali'。

我在做什么错?

Using the System.CommandLine v.2.0.0-beta3.22114.1 and System.CommandLine.NamingConventionBinder v.2.0.0-beta3.22114.1, I'm attempting to create a simple get command with a --name option.

The option is required. It expects an argument, and it will use it in the Console.WriteLine statement.

For the sake of organization, I am creating the commands in separate class files and inherit the Command class.

public class GetCommand : Command
{
    public GetCommand()
        :base("get", "Filters events by name.")
    {
        var name = new Option("--name", "The name of the event you like to fetch.")
        {
            IsRequired = true,
        };

        AddOption(name);
        Handler = CommandHandler.Create((string name) => Console.WriteLine(name));

        
    }
}

While running the app, when I run the executable with the get --name ali command, option, and argument, I keep getting the following exception:
Unrecognized command or argument 'ali'.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨洒年华 2025-02-01 18:47:13

对于参数的选项,您应该使用通用选项< t>。使用参数的类型作为类型参数:

new Option<string>(
    name: "--name", 
    description: "The name of the event you like to fetch."
) {
    IsRequired = true
}

For options that take an argument, you should use the generic Option<T>. Use the type of the argument as the type parameter:

new Option<string>(
    name: "--name", 
    description: "The name of the event you like to fetch."
) {
    IsRequired = true
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文