代码之家  ›  专栏  ›  技术社区  ›  Malfist

我怎样才能使这个lambda工作?

  •  1
  • Malfist  · 技术社区  · 15 年前

    我有这个代码:

            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”,因为它不是委托类型,“不能在此范围中声明名为“Temp”的局部变量,因为它将为“Temp”赋予不同的含义,后者已在“Parent or Current”范围中用于表示其他内容。”

    两个错误都在lambda行上。我怎么能做到这一点,我做错了什么?

    3 回复  |  直到 15 年前
        1
  •  5
  •   Elisha    15 年前
    this.Invoke(new Action(() => txtForm.Rtf = temp))
    
        2
  •  6
  •   Phil Ross Matt Johnson-Pint    15 年前

    “无法将lambda表达式转换为类型”System.Delegate“,因为它不是委托类型”,因为lambda表达式没有类型而发生错误。编译器通常从分配的目标推断类型,但这不可能与 Invoke 因为它需要 System.Delegate .强制转换lambda表达式将解决此问题。

    不需要申报 temp 作为lambda表达式的参数。表达式将能够引用 临时雇员 从包含范围。

    改变你的 援引 行到下面,它应该可以工作:

    this.Invoke((Action)(() => txtForm.Rtf = temp));
    

    确保您正在引用 System.Core 程序集,否则将出现一个错误,说明“使用泛型类型”System.Action“需要”1“类型参数”。

        3
  •  0
  •   leppie    15 年前
    this.Invoke((Action) () => txtForm.Rtf = something); // where something is free