让我们变得简单
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”(两者之间存在差异)