【问题标题】:How do you tell if an option was specified when using System.CommandLine?如何判断使用 System.CommandLine 时是否指定了选项?
【发布时间】:2021-12-18 02:36:15
【问题描述】:

使用 root 命令:

new RootCommand
{
    new Option<string>("--myoption")
};

你是怎么区分的

./myapp

./myapp --myoption ""

?

我最初假设如果未指定该选项将为 null,但事实并非如此,它是一个空字符串 :( 添加显式默认值 null 也不起作用;此代码仍会打印出 @987654325 @当没有选项传入时:

static void Main(string[] args)
{
    var rootCommand = new RootCommand
    {
        new Option<string>("--myoption", () => null)
    };
    rootCommand.Handler = CommandHandler.Create<string>(Run);
    rootCommand.Invoke(args);
}

private static void Run(string myoption)
{
    Console.WriteLine(myoption == null ? "(null)" : '"' + myoption + '"');
}

如果默认值设置为非空字符串,则默认值会按预期出现;只有null 神秘地变成了一个空字符串。

【问题讨论】:

    标签: c# command-line-arguments system.commandline


    【解决方案1】:

    您可以描述一个函数来计算默认值。如果使用 C# 8 或更高版本,您可能需要通过在末尾添加问号来明确说明您的字符串可以为空。

    new RootCommand
    {
        new Option<string?>("--myoption", () => null, "My option. Defaults to null");
    };
    

    我原以为这会起作用,但我能够在此处https://dotnetfiddle.net/uxyC8Y 的 dotnetfiddle 上设置一个工作示例,它显示即使每个参数都标记为可为空,它仍然作为空字符串返回。这可能是 System.CommandLine 项目的问题,所以我在这里提出了一个问题https://github.com/dotnet/command-line-api/issues/1459

    编辑:此问题仅在 2 天前通过此提交 https://github.com/dotnet/command-line-api/pull/1458/files 解决,此修复程序需要一些时间才能显示在已发布的 NuGet 包中,但最终将在库的未来版本中修复。

    如果不能使用空值,我唯一的建议是使用非常独特的默认字符串将值标记为未分配。

    const string defaultString = "Not Assigned.";
    static void Main(string[] args)
    {
        var rootCommand = new RootCommand
        {
            new Option<string>("--myoption", () => defaultString)
        };
        rootCommand.Handler = CommandHandler.Create<string>(Run);
        rootCommand.Invoke(args);
    }
    
    private static void Run(string myoption)
    {
        Console.WriteLine(myoption == defaultString ? "(null)" : '"' + myoption + '"');
    }
    

    【讨论】:

    • 我试过了;不幸的是,使用显式默认值null,它实际上仍然默认为空字符串!如果我有一个除null 之外的任何东西的明确默认值,那么这有效,但null 没有。我会更新问题。
    • @MarkRaymond 您是否使用带有可空引用的 C# 8 endjin.com/blog/2020/10/… ?我认为默认情况下 C# 8 不允许空值,除非您明确表示允许空值。我会用应该解决的方法更新我的答案。
    猜你喜欢
    • 2021-09-04
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多