开发者

How can I make this lambda work?

开发者 https://www.devze.com 2022-12-13 12:39 出处:网络
I have this code: String temp = txtForm.Rtf; foreach (ReplaceStrut rs in replaceArray) { temp = temp.Replace(rs.getNeedle(), rs.getReplacement());

I have this code:

        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;
        }

But it won't compile. It complains about two things, "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type" and, "A local variable named 'temp' cannot be declared in this scope because it would give a 开发者_JS百科difference meaning to 'temp', which is already used in a 'parent or current' scope to denote something else"

Both error are on the lambda line. How can I make this work, what am I doing wrong?


The "cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type" error is occurring because lambda expressions do not have types. The compiler usually infers the type from the target of the assignment, but this is not possible with Invoke because it takes a System.Delegate. Casting the lambda expression will solve this problem.

It isn't necessary to declare temp as a parameter of your lambda expression. The expression will be able to refer to temp from the containing scope.

Change your Invoke line to the following and it should work:

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

Make sure you are referencing the System.Core assembly for the above line, otherwise you'll get an error saying "Using the generic type 'System.Action' requires '1' type arguments".


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


this.Invoke((Action) () => txtForm.Rtf = something); // where something is free
0

精彩评论

暂无评论...
验证码 换一张
取 消