Mar*_*ond 6 c# command-line-arguments system.commandline
使用 root 命令:
new RootCommand
{
new Option<string>("--myoption")
};
Run Code Online (Sandbox Code Playgroud)
你如何区分两者之间的区别
./myapp
Run Code Online (Sandbox Code Playgroud)
和
./myapp --myoption ""
Run Code Online (Sandbox Code Playgroud)
?
我最初假设如果未指定该选项将为空,但事实并非如此,它是一个空字符串:(添加显式默认值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 + '"');
}
Run Code Online (Sandbox Code Playgroud)
如果默认值设置为非空字符串,则默认值确实会按预期显示;onlynull神秘地变成了一个空字符串。
您可以描述一个函数来计算默认值。如果使用 C# 8 或更高版本,您可能需要通过在末尾添加问号来明确说明您的字符串可为空。
new RootCommand
{
new Option<string?>("--myoption", () => null, "My option. Defaults to null");
};
Run Code Online (Sandbox Code Playgroud)
我本以为这会起作用,但我能够在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 + '"');
}
Run Code Online (Sandbox Code Playgroud)