开发者

C# => operator?

开发者 https://www.devze.com 2023-02-28 09:27 出处:网络
I have a question about the => operator in C#. I am looking at the Expression Blend 4 samples.There is one line in the Contact sample which includes:

I have a question about the => operator in C#.

I am looking at the Expression Blend 4 samples. There is one line in the Contact sample which includes:

//In C:\Program Files (x86)\Microsoft Expression\Blend 4\Samples\en\Contacts\
//Contacts\Vi开发者_JS百科ewModels\ContactsViewModel.cs: 

contactDetailWindow.Closed += (o, e) =>
{                              
   finishedCallback(contactDetailWindow.DialogResult);

   // Or, C:\Program Files (x86)\Microsoft Expression\Blend 4\Samples\en\
   // Contacts\Contacts\ViewModels\ContactsViewModel.cs
   this.EditContact(newContact, dialogResult =>
   {
        if (dialogResult.HasValue && dialogResult.Value)
        {
        this.Contacts.Add(newContact);
        }
   });
};

What is the => operator actually doing? Is it overriding something?


It's called the lambda operator.

 b.Click += (s, e) => Log("Sender :" + s + "EventArgs " + e);

is identical to

b.Click += b_Click;

void b_Click(object sender, EventArgs e)
{
    Log("Sender :" + sender + "EventArgs " + e);
}

or

b.Click += delegate(object sender, EventArgs e) 
           { 
               Log("Sender :" + sender + "EventArgs " + e);  
           };


=> is a lambda expression operator you can think of it as an anonymous function in javascript

in this case

ContactDetailWindow.Closed += (o, e) => { finishedCallback(contactDetailWindow.DialogResult);

it is creating a function that is being used as the handler for the closed event. The complier can infer the types of o and E since it knows the defintion of of the closed delelegate.


That's a lambda expression. The following defines an anoymous method expecting two parameters. Inside the curly brakets is obviously the body of the method:

(o, e) => { finishedCallback(contactDetailWindow.DialogResult)

Lambda expressions are hard to explain in a few sentences. I guess you have to have a look into the documentation and some examples.

0

精彩评论

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