首页 > 解决方案 > 在 .net core 3x 中,Regex Match,Groups 不能输入到 Enumerable extensions

问题描述

请考虑以下代码:

var regEx = new Regex("sample");
var match = regEx.Match("Some sample text");
var a = match.Groups.Skip(1).First().Name;

这将在 2.2 下编译和工作,但在 3.1 中编译错误:

error CS1061: 'GroupCollection' does not contain a definition for 'Skip' and no accessible extension method 'Skip' accepting a first argument of type 'GroupCollection' could be found (are you missing a using directive or an assembly reference?)

有趣的是,将其更改为:

var regEx = new Regex("sample");
var match = regEx.Match("Some sample text"); 
IEnumerable<Group> groups = match.Groups;
var a = groups.Skip(1).First().Name;

将修复错误。

为什么会出现此错误,以及哪些重大更改导致了此错误?

标签: c#linq.net-core

解决方案


这是由于这里的变化:https ://github.com/dotnet/corefx/pull/30077

根据讨论,如果甚至不被认为是一个重大更改,那么在任何更改日志中都没有提到它:

如果它在预览中被捕获,我们可能会恢复它;但鉴于我们已经发布了带有更改的 LTS 版本,它现在可能永远存在。

有点讽刺的是,我们今天在 API Review 中讨论了 IEnumerable 和 IReadOnlyDictonary 的重载歧义问题,但我们显然错过了扩展方法调用的歧义,因为它现在有两个不同的 IEnumerable。

建议包括使用 cast 来获取类型Enumerable

 int matches = m.Groups.Cast<Group>().Count(t => t.Success);

推荐阅读