带有匿名方法的BackgroundWorker?
我将使用匿名方法创建一个 BackgroundWorker。
我编写了以下代码:
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(
() =>
{
int i = 0;
foreach (var item in query2)
{
....
....
}
}
);
但是委托“System.ComponentModel.DoWorkEventHandler”不接受“0”参数并且我有将两个对象传递给匿名方法:对象发送者,DoWorkEventArgs e
您能否指导我,我该怎么做? 谢谢。
I'm gonna create a BackgroundWorker with an anonymous method.
I've written the following code :
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(
() =>
{
int i = 0;
foreach (var item in query2)
{
....
....
}
}
);
But Delegate 'System.ComponentModel.DoWorkEventHandler' does not take '0' arguments and I have to pass two objects to the anonymous method : object sender, DoWorkEventArgs e
Could you please guide me, how I can do it ?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只需要向匿名函数添加参数:
或者如果您不关心参数,您可以:
You just need to add parameters to the anonymous function:
Or if you don't care about the parameters you can just:
如果指定 lambda,则必须确保它采用相同数量的参数:
但如果不使用参数,则可以仅使用不带参数的匿名委托:
If you specify a lambda, you must ensure it takes the same number of arguments:
But if you're not using the arguments, you could just use an anonymous delegate without parameters:
如果你在没有 lambda 的情况下编写了上面的内容,那会怎么样?
和命名方法:
但现在您使用的是没有绑定变量的 lambda ()=>;
您应该提供两个对象 sender 和 e (稍后将推断它们的类型)。
If you have written the above without lambdas how it would be?
and the named method:
But now you are using lambdas with no bound variables ()=>
You should provide two objects sender and e (which they will get type inferred later).
让我们变得简单
Lambda 表达式对于使代码更短、更具可读性来说非常方便。然而,入门级程序员可能会发现它有点难以处理。应该了解三个独立的概念:匿名方法、委托和 lambda 表达式。每个问题的详细介绍超出了本答案的范围。我希望下面给出的代码示例能够帮助您快速了解可用的不同方法。
请注意,在本例中我们使用的是“delegate”而不是“Delegate”(两者之间是有区别的)
Lets make it simple
Lambda expressions are really handy to make the code shorter and more readable. However entry level programmers might find it a bit difficult to deal with. There are three separate concepts one should go through: anonymous methods, delegates and lambda expressions. A detailed walk-through of each of them is beyond the scope of this answer. I hope that the code example given below will serve the purpose of giving a quick view of the different approaches available.
Note that we used "delegate" and not "Delegate" in this example (there is a difference between the two)