Skip to main content
 首页 » 编程设计

c#之Parallel.ForEach 与 MatchCollection

2024年02月13日13sharpest

首先,我知道这是 this question 的副本,但我无法获得此处列出的适合我的解决方案。我知道 MatchCollection 没有实现 IEnumerable Parallel.ForEach 的使用,因此需要 OfType() ......知道我做错了什么吗?这是我的设置:

MatchCollection startMatches = Regex.Matches(tempRTB.Text, startPattern); 
 
System.Threading.Tasks.Parallel.ForEach(startMatches.OfType<Match>, m => 
{ 
    // do stuff with m 
}); 

这是我得到的编译错误:

Error   11  The type arguments for method 'System.Threading.Tasks.Parallel.ForEach<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Action<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

请您参考如下方法:

你所缺少的只是()(OfType是一个静态扩展方法)

System.Threading.Tasks.Parallel.ForEach(startMatches.OfType<Match>(), m => 
        { 
            // do stuff with m 
        });