开发者

What is this event?

Could someone explain what this C# code is doing?

// launch the camera capture when the user touch the screen
this.MouseLeftButtonUp += (s, e) => new CameraCaptureTask().Show();
开发者_如何学JAVA
// this static event is raised when a task completes its job
ChooserListener.ChooserCompleted += (s, e) =>
{
    //some code here
};

I know that CameraCaptureTask is a class and has a public method Show(). What kind of event is this? what is (s, e)?


When attaching event handlers, you can do in three different ways:

The old fashioned verbose way:

this.MouseLeftButtonUp += Handle_MouseLeftButtonUp;
void Handle_MouseLeftButtonUp(object s, MouseButtonEventArgs e)
{
  new CameraCaptureTask().Show(); 
}

An anonymous method:

this.MouseLeftButtonUp += delegate(object s, MouseButtonEventArgs e) {
  new CameraCaptureTask().Show(); 
}

Or, using a lambda expression:

this.MouseLeftButtonUp += (s, e) => new CameraCaptureTask().Show(); 

Imagine the last one as a 'compact form' of the one using the delegate. You could also use braces:

this.MouseLeftButtonUp += (s, e) => {
  new CameraCaptureTask().Show(); 
}


(s, e) => new CameraCaptureTask().Show();

This is an anonymous delegate (lambda expression). This takes 2 parameters (s and e (which are unused)), and then create a new CameraCaptureTask and show it.


Lambda notation, s stands for sender, e for eventargs, the event's arguments.


(s, e) => { }

is a lambda expression. In this case, it's just a quick way of defining a method (an inline method) without having to create a separate method in the class.


As mentioned, the syntax you are seeing is a lambda expression. The code you have in a simplistic view is a short hand for the following

this.MouseLeftButtonUp += Handle_MouseLeftButtonUp;

void Handle_MouseLeftButtonUp(object s, MouseButtonEventArgs e)
{
  new CameraCaptureTask().Show(); 
}

Check the references others have given, Lambda expression provide far more.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜