这行C#代码实际上做了什么?

Nic*_*ckG 4 c# events delegates

我试图理解应用程序中的代码块是什么,但我遇到了一些C#我只是不明白.

在下面的代码中,"controller.Progress + ="行之后的代码是做什么的?

我之前没有看过这种语法,因为我不知道这些结构是什么,我不能谷歌任何东西来找出这种语法的意思或作用.例如,值s和p是什么?他们是占位符吗?

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    using (var controller = new ApplicationDeviceController(e.Argument as SimpleDeviceModel))
    {
        controller.Progress += 
           (s, p) => { (sender as BackgroundWorker).ReportProgress(p.Percent); };
        string html = controller.GetAndConvertLog();
        e.Result = html;
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来它正在将一个函数附加到一个事件,但我只是不理解语法(或者s和p是什么),并且在该代码上没有有用的intellsense.

Edu*_*coz 6

它是一个分配给事件处理程序的lambda表达式.

S和P是传递给函数的变量.你基本上定义了一个无名函数,它接收两个参数.因为C#知道controller.Progress事件需要一个方法处理程序,它有两个类型为int和object的参数,所以它会自动假设这两个变量属于这些类型.

您也可以将其定义为

controller.Progress += (int s, object p)=> { ... }
Run Code Online (Sandbox Code Playgroud)

它就像你有一个方法定义一样:

controller.Progress += DoReportProgress;
....
public void DoReportProgress(int percentage, object obj) { .... }
Run Code Online (Sandbox Code Playgroud)