我的 System.CommandLine 应用无法构建!它找不到 CommandHandler。我需要写吗?

My System.CommandLine app won't build! It can't find a CommandHandler. Do I need to write it?

我正在使用 VS 2022、.Net 6.0,并尝试使用 System.CommandLine 构建我的第一个应用程序。

问题:构建时出现错误

The name 'CommandHandler' does not exist in the current context

我尝试构建的代码是来自 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 parsed as a FileInfo")
    };

    rootCommand.Description = "My sample app";

    // Note that the parameters of the handler method are matched according to the names of the options
    rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
    {
        Console.WriteLine($"The value for --int-option is: {intOption}");
        Console.WriteLine($"The value for --bool-option is: {boolOption}");
        Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
    });

    // Parse the incoming args and invoke the handler
    return rootCommand.InvokeAsync(args).Result;
}

我已经安装了最新版本System.Commandline:2.0.0-beta2.21617.1

当然我在某些方面只是个大胖白痴。但是我没看到。

欢迎任何见解。

认为您缺少 using 行:

using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;

我不能发誓就是这样,但看起来 CommandHandler 是在未被 using 引用的命名空间中定义的(在您当前的代码中),因此 System.CommandLine.Invocation 可能成为关键!

此问题是由更新 CommandLine 2.0 Beta 2 包引起的。将引用 System.CommandLine.NamingConventionBinder 添加到引用以修复问题。请关注命令行-api 的 GitHub 帐户上的公告:

In your project, add a reference to System.CommandLine.NamingConventionBinder.

In your code, change references to the System.CommandLine.Invocation namespace to use System.CommandLine.NamingConventionBinder, where the CommandHandler.Create methods are now found. (There’s no longer a CommandHandler type in System.CommandLine, so after you update you’ll get compilation errors until you reference System.CommandLine.NamingConventionBinder.)

如果您想继续使用旧习惯,请尝试使用旧版本的 System.CommandLine 软件包。


参考资料