我正在使用 VS 2022、.Net 6.0,并尝试使用 .Net 构建我的第一个应用程序System.CommandLine。
问题:当我构建它时,出现错误
当前上下文中不存在名称“CommandHandler”
我尝试构建的代码是来自 GitHub 站点的示例应用程序:https ://github.com/dotnet/command-line-api/blob/main/docs/Your-first-app-with-System-CommandLine .md,无需更改(我认为)。
它看起来像这样:
using System;
using System.CommandLine;
using System.IO;
static int Main(string[] args)
{
// Create a root command with some options
var rootCommand = new RootCommand
{
new Option<int>(
"--int-option",
getDefaultValue: () => 42,
description: "An option whose argument is parsed as an int"),
new Option<bool>(
"--bool-option",
"An option whose argument is parsed as a bool"),
new Option<FileInfo>(
"--file-option",
"An option whose argument is …Run Code Online (Sandbox Code Playgroud) 使用 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神秘地变成了一个空字符串。
我正在尝试使用System.CommandLine并安装了 nuget 软件包:
Install-Package System.CommandLine -Version 2.0.0-beta1.21308.1
Run Code Online (Sandbox Code Playgroud)
根据这篇 Microsoft 文章,我应该能够使用我的签名编写一个 Main() 方法,并且它应该会自动神奇地工作:
static void Main(FileInfo input, FileInfo output)
{
Console.WriteLine($"Hello World! {input} {output}");
}
Run Code Online (Sandbox Code Playgroud)
但是我的 Main() 方法签名被拒绝,我得到了CS5001: Program does not contain a static 'Main' method suitable for an entry point.
难道我做错了什么?根据这篇文章,这System.CommandLine应该是如何工作的。
对于 F# 应用程序,我传统上使用不同的功能友好的命令行解析器,例如Argu和CommandLineParser。
既然 Microsoft 已经推出了System.CommandLine(可能会带来更好的支持和文档),它可以在 F# 中使用吗?