Reputation: 3611
I'm using this code with .NET 3.0
Action xx = () => button1.Text = "hello world";
this.Invoke(xx);
but when i tried it in .NET 2.0, I think Action has type parameter like this:
Action<T>
How to implement the first code in .NET 2.0?
Upvotes: 5
Views: 513
Reputation: 48730
Action<T>
is the signature, which just means that the method represented by the action must take a single parameter. What the type of the parameter is, depends on the signature of the Invoke
call.
Some code examples of how to represent the various signatures of Action
:
var noArgs = () => button1.Text = "hello world"; // Action
var oneArg = (arg) => button1.Text = "hello world"; // Action<T>
var twoArgs = (arg1, arg2) => button1.Text = "hello world"; // Action<T,T>
If you don't need to use the parameters to the method, that's fine. But you still need to declare them in the lambda expression.
Now, this doesn't answer how to do it from .NET 2.0, but I assumed (perhaps incorrectly, correct me if I'm wrong) that you weren't aware how lambdas correspond to Action types.
Upvotes: 1
Reputation: 78507
Try this:
this.Invoke((MethodInvoker) delegate
{
button1.Text = "hello world";
});
Although Action
was introduced in .NET 2.0, you cannot use lambda expression () => ...
syntax in .NET 2.0.
BTW, you can still use Action
in .NET 2.0, as long as you don't use lambda sytax:
Action action = delegate { button1.Text = "hello world"; };
Invoke(action);
Upvotes: 6