c# - 未提供参数时如何指定 C# System.Commandline 行为?

标签 c# console-application system.commandline

在我的控制台应用程序中,当未提供控制台参数时,将执行我指定列表(本例中为参数 3)的处理程序。调用该处理程序时, bool 参数设置为 false。但对我来说,根本不调用它更有意义。

如何防止这种情况发生并显示帮助文本?

using System;
using System.CommandLine;

namespace GlideRush.LeaderboardsConsole // Note: actual namespace depends on the project name.
{
    internal class Program
    {
        static async Task<int> Main(string[] args)
        {
            var test1 = new Option<bool>(
                name: "test1",
                description: "test param 1");
            var test2 = new Option<bool>(
                name: "test2",
                description: "test param 2");
            var test3 = new Option<bool>(
                name: "test3",
                description: "test param 3");

            var rootCommand = new RootCommand("Testing console params");

            rootCommand.AddOption(test1);
            rootCommand.AddOption(test2);
            rootCommand.AddOption(test3);

            rootCommand.SetHandler(boolparam => Console.WriteLine($"Param 1 {boolparam}"), test1);
            rootCommand.SetHandler(boolparam => Console.WriteLine($"Param 2 {boolparam}"), test2);
            rootCommand.SetHandler(boolparam => Console.WriteLine($"Param 3 {boolparam}"), test3);

            return await rootCommand.InvokeAsync(args);
        }
    }
}

当我不提供参数时,它输出:

$ dotnet run
Param 3 False

我希望它输出默认值:

Description:
  Testing console params

Usage:
  GlideRushConsole [options]

Options:
  test1           test param 1
  test2           test param 2
  test3           test param 3
  --version       Show version information
  -?, -h, --help  Show help and usage information

让处理程序的顺序确定默认行为感觉不对,我也不想检查每个参数处理程序上的 bool 是否为 false。无论如何,这仍然没有给我默认的帮助菜单。

最佳答案

单个命令只能有一个处理程序,如 Panagiotis Kanavos已经说过了。

如果您想要基于参数的不同处理程序,您可能正在寻找 for subcommands or verbs .

例如(徒手代码)

var smoothOrNot = new Option<bool>(
            name: "smooth",
            description: "smooth gliding or nah?");
var fastOrNot = new Option<bool>(
            name: "fast",
            description: "fast gliding or prefer slow");

var glideRushCommand = new RootCommand();
var glideVerb = new Command("glide", "glide subcommand");
var rushVerb = new Command("rush", "rush subcommand");
glideVerb.Add(glideOptionOne);
glideVerb.Add(glideOptionTwo);
glideRushCommand.Add(glideVerb);

关于c# - 未提供参数时如何指定 C# System.Commandline 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74111111/

相关文章:

Linux 控制台输出被 ASCII 字符损坏

objective-c - 如何在 Objective C 中编写日志文件?

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

c# - 类和方法

c# - 你能分配一个没有 TypeConverterAttribute 的 TypeConverter 吗?

c# - 使用 C# 解析 Resx 文件在相对路径上崩溃

c# - 如何将 Unicode 字符写入控制台?

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

c# - DTO 中的枚举类型命名约定