我需要帮助将此for循环转换为并行forloop。
public void spellchecker()
{
Invoke(new MethodInvoker(delegate ()
{
using (Hunspell hunspell = new Hunspell("en_us.aff", "en_US.dic"))
{
foreach (Match match in Regex.Matches(GetRichTextBox().Text, @"\w+"))
{
string word = match.Value;
Font fnt = GetRichTextBox().Font;
Color color;
if (!hunspell.Spell(word))
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Underline);
color = Color.Red;
}
else
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Regular);
color = Color.Black;
}
GetRichTextBox().Select(match.Index, match.Length); // Selecting the matching word.
GetRichTextBox().SelectionColor = color;
GetRichTextBox().SelectionStart = GetRichTextBox().TextLength; // Resetting the selection.
GetRichTextBox().SelectionLength = 0;
}
}
}));
}
当我尝试实现并行for循环时,这是我的实现。我一直收到一条错误消息&#34; Arguments for method'Parallel.ForEach<TSource>(IEnumereable<TSourcce>,Action<TSource>
)&#39;无法从使用情况中推断出<#34;
Parallel.ForEach(Regex.Matches(GetRichTextBox().Text, @"\w+"), match => {
string word = match.Value;
Font fnt = GetRichTextBox().Font;
Color color;
if (!hunspell.Spell(word))
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Underline);
color = Color.Red;
}
else
{
fnt = new Font(fnt.FontFamily, fnt.Size, FontStyle.Regular);
color = Color.Black;
}
GetRichTextBox().Select(match.Index, match.Length); // Selecting the matching word.
GetRichTextBox().SelectionColor = color;
GetRichTextBox().SelectionStart = GetRichTextBox().TextLength; // Resetting the selection.
GetRichTextBox().SelectionLength = 0;
});
答案 0 :(得分:4)
Parallel.ForEach()希望IEnumerable<T>
获得第一个参数。必须从该类型参数推断出TSource
,因为第二个参数是一个lambda表达式,其自身参数没有声明的类型。 Regex.Matches(string, string)返回MatchCollection
,它实现非通用System.Collections.IEnumerable
,不 IEnumerable<T>
。它早于仿制药。因此,编译器无法推断出TSource
是什么。
但我们知道TSource
应为Match
。所以使用Cast<T>()
:
Parallel.ForEach(Regex.Matches(GetRichTextBox().Text, @"\w+").Cast<Match>(),
match => {
你可以明确地说lambda的参数是Match
:
Parallel.ForEach(Regex.Matches(GetRichTextBox().Text, @"\w+"), (Match match) =>
您将不再获得类型推断错误。但是,您仍然会收到有关IEnumerable的错误,因为MatchCollection
仍然无法实现通用IEnumerable<T>
:
错误CS1503:参数1:无法转换为&#39; System.Text.RegularExpressions.MatchCollection&#39;到&#39;
System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>
&#39;
顺便说一句,这就是为什么你不能在var
foreach
上MatchCollection
使用Match
而没有明确地将循环变量声明为m
或将其转换为object
循环体:基于编译器知道的所有内容,foreach (var m in Regex.Matches("foo", "[0-9]"))
{
var caps = m.Captures;
}
为<div class="alert alert-danger" *ngIf="courseCategory.touched && !courseCategory.valid">
。
NgModel
错误CS1061:&#39;对象&#39;不包含&#39; Captures&#39;的定义没有延伸方法&#39;捕获&#39;接受类型&#39;对象&#39;的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)