使用根命令:
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/