简体   繁体   中英

What does this line of C# code actually do?

I'm trying to understand what a block of code in an application does but I've come across a bit of C# I just don't understand.

In the code below, what does the code after the "controller.Progress +=" line do?

I've not seen this syntax before and as I don't know what the constructs are called, I can't google anything to find out what this syntax means or does. What for instance, are the values s and p? Are they placeholders?

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;
    }
}

It looks like it's attaching a function to an event, but I just don't understand the syntax (or what s and p are) and there's no useful intellsense on that code.

It's a lambda expression being assigned to an event handler.

S and P are variables that are passed into the function. You're basically defining a nameless function, that receives two parameters. Because C# knows that the controller.Progress event expects a method handler with two parameters of types int and object, it automatically assumes that the two variables are of those types.

You could also have defined this as

controller.Progress += (int s, object p)=> { ... }

It's the same as if you had a method definition instead:

controller.Progress += DoReportProgress;
....
public void DoReportProgress(int percentage, object obj) { .... }

It wires up the Progress event of controller to trigger the BackgroundWorker's ReportProgress

More specifically, (s, p) is the Method Parameter Signature for the event handler, like (object Sender, EventArgs e)

See lambda expressions

It's called an Anonymous Function .

An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

In your scenario, it is basically wiring up your Progress event to trigger the ReportProgess function.

Normally, it would be written something like:

controller.Progress += new EventHandler(delegate (object sender, EventArgs a) {
    (sender as BackgroundWorker).ReportProgress(p.Percent);
});

Actually this code assigns the lambda exp to the event. In compile time it will be converted as delegates as follows,

controller.Progress += new EventHandler(delegate (Object o, EventArgs a) {
a.ReportProgress(p.Percent);
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM