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

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

使用根命令:

new RootCommand
{
    new Option<string>("--myoption")
};
你怎么区分
./myapp
./myapp --myoption ""
?
我最初假设如果未指定该选项将为 null,但事实并非如此,它是一个空字符串 :( 添加显式默认值 null 也不起作用;此代码在没有时仍会打印出 ""选项传入:
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# 8 或更新版本,您可能需要通过在末尾添加问号来明确说明您的字符串可以为空。

new RootCommand
{
    new Option<string?>("--myoption", () => null, "My option. Defaults to null");
};
我原以为这会奏效,但我能够在 dotnetfiddle 上设置一个工作示例 https://dotnetfiddle.net/uxyC8Y这表明即使每个参数都标记为可空,它仍然作为空字符串返回。这可能是 System.CommandLine 项目的问题,所以我在这里提出了一个问题 https://github.com/dotnet/command-line-api/issues/1459
编辑:此问题仅在 2 天前通过此提交解决 https://github.com/dotnet/command-line-api/pull/1458/files此修复程序出现在已发布的 NuGet 包中需要一些时间,但最终将在库的 future 版本中修复。
由于无法使用空值,我唯一的建议是使用一个非常不同的默认字符串来将值标记为未分配。
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 + '"');
}

关于c# - 如何判断在使用 System.CommandLine 时是否指定了一个选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69829523/

相关文章:

c# - gridview 中的 Oracle 数据库表

delphi - 为什么当应用程序由 IDE 与启动器启动时,命令行参数的数量会发生变化?

c# - System.CommandLine命令自定义验证器: how to search

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

c# - 如何在 Xamarin iOS SQLite 中添加 SQLiteOpenFlags.FullMutex 标志

c# - 如何将字符串数组转为int数组进行计算?

C 编程 - 基于命令行参数的数组大小

C# Form1.cs 不再显示在解决方案资源管理器中

比较 C 字符串与字符串指针的相等性