我正在使用VisualStudioforMacOS2022v17.4和System.CommandLine(2.0.0-beta4.22272.1)编写一个C#控制台应用程序项目(.NET 7.0).

我正在try 向我的一个命令添加自定义验证器,并在项目的GitHub站点上找到了以下代码片段:

        this.AddValidator(commandResult =>
        {
            if (commandResult.Children.Contains("one") &&
                commandResult.Children.Contains("two"))
            {
               commandResult.ErrorMessage = "Options '--one' and '--two' cannot be used together.";
            }
        });

但是,由于错误CS1929,它不会在我的命令中编译:‘IReadOnlyList’不包含‘Containers’的定义,并且最佳扩展方法重载‘M一带一路’(ReadOnlySpan,字符串)需要类型为‘ReadOnlySpan’的接收器(CS1929).

我在各种System.CommandLine命名空间中寻找了合适的扩展方法,但我什么也没看到.(是的,我包括了System.Linq命名空间.)

有谁能建议一下哪里出了问题吗?

编辑:我borrow 的原始代码是这样的:

        command.AddValidator(commandResult =>
        {
            if (commandResult.Children.Contains("one") &&
                commandResult.Children.Contains("two"))
            {
                return "Options '--one' and '--two' cannot be used together.";
            }

            return null;
        });

请注意,此委托返回值,而更新后的委托不返回值,而是设置ErrorMessage.这是System.CommandLine中的一个突破性更改,这里的问题可能是由于另一个突破性更 retrofit 成的.System.CommandLine项目does指出,该项目处于不断变化的状态,并且可能会发生变化.

推荐答案

我没有使用这个特定库的经验,但查看它的源代码会提示您调用.Contains()的集合不包含String,而是SymbolResult的实例,因此它无法为您try 调用的方法找到合适的重载.

我在前面提到的GitHub repo中找不到您提供的代码,而是从this test file个库中找到了这段代码:

command.Validators.Add(commandResult =>
{
    if (commandResult.Children.Any(sr => sr.Symbol is IdentifierSymbol id && id.HasAlias("--one")) &&
        commandResult.Children.Any(sr => sr.Symbol is IdentifierSymbol id && id.HasAlias("--two")))
        {
            commandResult.ErrorMessage = "Options '--one' and '--two' cannot be used together.";
        }
});

Csharp相关问答推荐

需要更改哪些内容才能修复被覆盖的财产中的无效警告CS 8765?

C# uwp中的Win11启动屏幕剪辑工作方式不同

子组件:如何根据另一个组件的状态启用输入

如何在Visual Studio中为C# spread操作符设置格式规则?

总是丢弃返回的任务和使方法puc无效之间有区别吗?

在命令行中使用时安装,但在单击时不会安装

Microsoft. VisualBasic. FileIO. FileSystem. MoveFile()对话框有错误?

在FilePath中搜索一个词,并根据First Match从左到右提取文件路径

从c#列表中删除额外的对象&对象&>从ASP.NET WebForm返回json响应

C#阻塞调用或await calling inside calling方法

如何将字符串变量传递给JObject C#-无法加载文件或程序集';System.Text.Json

使用Dapper映射联接查询对象数据到使用SplitOn;

如何使用.NET6WPF打印车票?

具有可空类型的C#NOTNULL约束具有意外行为

GODOT 4向C#中的字符串参数发送信号以等待

使用System.Text.Json进行序列化时发生StackOverflow异常

C#按名称从类获取属性值类型<;t>;,我需要反射吗?

错误CS1061';AuthenticationBuilder';不包含AddOpenIdConnect的定义

VS 2022与VS 2019:如何/为什么创建额外的任务?

工厂类是如何在.NET 8中注册的?