加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – SmartEnumerable和Regex.Matches

发布时间:2020-12-16 01:39:06 所属栏目:百科 来源:网络整理
导读:我想使用Jon Skeet的 SmartEnumerable循环一个Regex.Matches,但它不起作用. foreach (var entry in Regex.Matches("one :two",@"(?!w):(w+)").AsSmartEnumerable()) 有人可以解释一下为什么吗?并提出一个解决方案,使其工作.谢谢. 错误是: 'System.Text.R
我想使用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?)

解决方法

编辑:我想你忘了在示例代码中插入.AsSmartEnumerable()调用.无法编译的原因是因为extension-method仅适用于IEnumerable< T>,而不适用于非通用IEnumerable接口.

并不是说你不能用这种方式枚举比赛;只是因为MatchCollection类没有实现通用的IEnumerable< T>,所以条目的类型将被推断为对象.接口,只有IEnumerable接口.

如果你想坚持使用隐式类型,你将不得不产生一个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)
{
   ...
}

这将需要使用MiscUtil.Collections.Extensions;源文件中的指令.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读