SmartEnumerable和Regex.Matches

Luk*_*sky 3 c# regex ienumerable

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

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

有人可以解释一下为什么吗?并提出一个解决方案,使其工作.谢谢.

错误是:

'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?)
Run Code Online (Sandbox Code Playgroud)

Ani*_*Ani 7

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


并不是说你不能用这种方式枚举比赛; 它只是因为类没有实现泛型接口而只是接口entry而推断的类型.objectMatchCollectionIEnumerable<T>IEnumerable

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

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

或者,使用显式输入的更好方法(编译器为您插入一个强制转换):

foreach (Match entry in Regex.Matches("one :two", @"(?<!\w):(\w+)"))
{ 
   ...
} 
Run Code Online (Sandbox Code Playgroud)

生成智能可枚举的最简单方法是使用提供的扩展方法:

var smartEnumerable = Regex.Matches("one :two", @"(?<!\w):(\w+)")
                           .Cast<Match>()
                           .AsSmartEnumerable();

foreach(var smartEntry in smartEnumerable)
{
   ...
}
Run Code Online (Sandbox Code Playgroud)

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

  • 您需要在文件顶部使用`using System.Linq`指令. (3认同)