What does this line of code in C # do?

I'm trying to figure out what a block of code in an application does, but I came across a bit of C #, I just don't get it.

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

I have not seen this syntax yet, and since I do not know what is caused by the constructs, I cannot understand what this syntax means or does. What are the values ​​of s and p, for example? 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 seems like it binds the function to the event, but I just don't understand the syntax (or what s and p are), and there is no useful intellsense in this code.

+4
source share
4 answers

This lambda expression is assigned to an event handler.

S and P are variables that are passed to the function. You basically define an anonymous function that takes two parameters. Since C # knows that the controller.Progress event expects a method handler with two parameters of the int and object types, it automatically assumes that these two variables are of these types.

You could also define this as

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

This is the same as if you had a method definition:

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

It raises the Progress controller event to raise the BackgroundWorker's ReportProgress

More specifically, (s, p) is the signature of the method parameter for the event handler, for example (object Sender, EventArgs e)

See lambda expressions

+3
source

He called the Anonymous function .

An anonymous function is a "built-in" 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 the name of a delegated type as a parameter to a method.

In your scenario, this is basically posting your Progress event to trigger the ReportProgess function.

Usually it would be written something like this:

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

In fact, this code assigns the lambda event exp. At compile time, it will be converted as delegates as follows:

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

Source: https://habr.com/ru/post/1480731/


All Articles