BackgroundWorker有匿名方法吗?

我将使用匿名方法创建BackgroundWorker
我写了以下代码:

BackgroundWorker bgw = new BackgroundWorker(); bgw.DoWork += new DoWorkEventHandler( () => { int i = 0; foreach (var item in query2) { .... .... } } ); 

但是委托’System.ComponentModel.DoWorkEventHandler’不接受’0’参数 ,我必须将两个对象传递给匿名方法: object sender,DoWorkEventArgs e

你能指导我,我该怎么办? 谢谢。

您只需要向匿名函数添加参数:

 bgw.DoWork += (sender, e) => { ... } 

或者,如果您不关心参数,您可以:

 bgw.DoWork += delegate { ... } 

如果指定lambda,则必须确保它具有相同数量的参数:

 bgw.DoWork += (s, e) => ...; 

但是如果你没有使用参数,你可以使用没有参数的匿名委托:

 bgw.DoWork += delegate { ... }; 

如果你在没有lambdas的情况下写了上面的内容怎么样?

 backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork); 

和命名的方法:

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { // Get the BackgroundWorker that raised this event. BackgroundWorker worker = sender as BackgroundWorker; // Assign the result of the computation // to the Result property of the DoWorkEventArgs // object. This is will be available to the // RunWorkerCompleted eventhandler. e.Result = ComputeFibonacci((int)e.Argument, worker, e); } 

但是现在你使用没有绑定变量的lambdas()=>你应该提供两个对象sender和e(稍后会推断它们的类型)。

 backgroundWorker1.DoWork += (sender, e) => ... 

让我们简单一点

Lambda表达式非常方便使代码更短,更易读。 然而,入门级程序员可能会觉得处理起来有点困难。 应该经历三个独立的概念:匿名方法,委托和lambda表达式。 详细介绍每一个都超出了这个答案的范围。 我希望下面给出的代码示例能够快速查看可用的不同方法。

 class TestBed { BackgroundWorker bgw = new BackgroundWorker(); void sample() { //approach #1 bgw.DoWork += new DoWorkEventHandler(bgw_DoWork); //DoWorkEventHandler is nothing but a readily available delegate written by smart Microsoft guys //approach #2, to make it a little shorter bgw.DoWork += (s,e) => { //... }; //this is called lambda expression (see the => symbol) //approach #3, if lambda scares you bgw.DoWork += delegate { //... (but you can't have parameters in this approach }; //approach #4, have a helper method to prepare the background worker prepareBgw((s,e)=> { //... } ); //approach #5, helper along with a simple delegate, but no params possible prepareBgw(delegate { //... } ); //approach #6, helper along with passing the methodname as a delegate prepareBgw(bgw_DoWork); //approach #7, helper method applied on approach #1 prepareBgw(new DoWorkEventHandler(bgw_DoWork)); } void bgw_DoWork(object sender, DoWorkEventArgs e) { //... } void prepareBgw(DoWorkEventHandler doWork) { bgw.DoWork+= doWork; } } 

请注意,我们在此示例中使用了“delegate”而不是“Delegate”(两者之间存在差异)