SmartEnumerable and Regex.Matches

3

我想使用Jon Skeet的SmartEnumerable来循环遍历Regex.Matches,但它不起作用。

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").AsSmartEnumerable())

请问有人可以解释一下这个问题吗?并提供一个解决方案使之可以工作。谢谢。

错误信息如下:
'System.Text.RegularExpressions.MatchCollection' does not contain a definition
for 'AsSmartEnumerable' and no extension method 'AsSmartEnumerable' accepting
a first argument of type 'System.Text.RegularExpressions.MatchCollection' could
be found (are you missing a using directive or an assembly reference?)
1个回答

7

编辑:我认为您忘记在示例代码中插入.AsSmartEnumerable()调用了。 原因是该扩展方法仅适用于IEnumerable<T>,而不适用于非泛型IEnumerable接口,所以那样无法编译。


并不是说您不能以这种方式枚举匹配项;只是由于MatchCollection类没有实现泛型IEnumerable<T>接口,而仅实现了IEnumerable接口,所以entry的类型将被推断为object

如果您想坚持使用隐式类型,则必须生成一个IEnumerable<T>以帮助编译器:

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").Cast<Match>())
{ 
   ...
} 

或者,更好的方式是使用显式类型(编译器会为您插入转换):
foreach (Match entry in Regex.Matches("one :two", @"(?<!\w):(\w+)"))
{ 
   ...
} 

使用提供的扩展方法是生成智能可枚举的最简单方法:
var smartEnumerable = Regex.Matches("one :two", @"(?<!\w):(\w+)")
                           .Cast<Match>()
                           .AsSmartEnumerable();

foreach(var smartEntry in smartEnumerable)
{
   ...
}

这将需要在源文件中添加using MiscUtil.Collections.Extensions;指令。

强制转换在我的.NET 4中无法工作:'System.Text.RegularExpressions.MatchCollection'不包含定义为'Cast'的内容,也没有接受类型为'System.Text.RegularExpressions.MatchCollection'的第一个参数的扩展方法'Cast'(您是否缺少使用指令或程序集引用?) - Lukas Cenovsky
3
你需要在文件顶部加入 using System.Linq 指令。 - Ani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接