我有这个代码:
String temp = txtForm.Rtf;
foreach (ReplaceStrut rs in replaceArray) {
temp = temp.Replace(rs.getNeedle(), rs.getReplacement());
}
if (this.InvokeRequired) {
this.Invoke(temp => txtForm.Rtf = temp);
} else {
txtForm.Rtf = temp;
}
但是它不会编译。它提示两件事,“无法将 lambda 表达式转换为‘System.Delegate’类型,因为它不是委托(delegate)类型”和“无法在此范围内声明名为‘temp’的局部变量,因为它会给'temp',它已经在'parent or current'范围内使用来表示其他东西"
两个错误都在 lambda 行上。我怎样才能完成这项工作,我做错了什么?
最佳答案
“无法将 lambda 表达式转换为‘System.Delegate’类型,因为它不是委托(delegate)类型”错误是因为 lambda 表达式没有类型。编译器通常从赋值目标推断类型,但这对于 Invoke
是不可能的,因为它需要一个 System.Delegate
。转换 lambda 表达式将解决这个问题。
没有必要将 temp
声明为 lambda 表达式的参数。该表达式将能够从包含范围引用 temp
。
将您的 Invoke
行更改为以下内容,它应该可以工作:
this.Invoke((Action)(() => txtForm.Rtf = temp));
确保您在上面的行中引用了 System.Core
程序集,否则您将收到一条错误消息“使用通用类型‘System.Action’需要‘1’类型参数” .
关于c# - 我怎样才能使这个 lambda 起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852618/