开发者

What is '=>'? (C# Grammar Question) [duplicate]

开发者 https://www.devze.com 2022-12-28 05:13 出处:网络
This question already has answers here: 开发者_如何学C What does the '=>' syntax in C# mean?
This question already has answers here: 开发者_如何学C What does the '=>' syntax in C# mean? (7 answers) Closed 8 years ago.

I was watching a Silverlight tutorial video, and I came across an unfamiliar expression in the example code.

what is => ? what is its name? could you please provide me a link? I couldn't search for it because they are special characters.

code:

        var ctx = new EventManagerDomainContext();
        ctx.Events.Add(newEvent);
        ctx.SubmitChanges((op) =>
        {
            if (!op.HasError)
            {
                NavigateToEditEvent(newEvent.EventID);
            }
        }, null);


It's a lambda expression.

If you're familiar with anonymous methods from C# 2, lambda expressions are mostly similar but more concise. So the code you've got could be written like this with an anonymous method:

var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges(delegate(Operation op)
{
    if (!op.HasError)
    {
        NavigateToEditEvent(newEvent.EventID);
    }
}, null);

Aspects of anonymous methods such as the behaviour of captured variables work the same way for lambda expressions. Lambda expressions and anonymous methods are collectively called anonymous functions.

There are a few differences, however:

  • Lambda expressions can be converted into expression trees as well as delegates.
  • Lambda expressions have a number of shortcuts to make them more concise:

    • If the compiler can infer the parameter types, you don't need to specify them
    • If the body is a single statement, you don't need to put it in braces and you can omit the "return" part of a return statement
    • If you have a single parameter with an inferred type, you can miss out the brackets

    Putting these together, you get things like:

    IEnumerable<string> names = people.Select(person => person.Name);
    
  • Lambda expressions don't support the "I don't care how many parameters there are" form of anonymous methods, e.g.

    EventHandler x = delegate { Console.WriteLine("I was called"); };
    


Lambda operator:

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls...

Huzzah!


I couldn't search for it because they are special characters.

Sometimes the old-fashioned ways are the best. This worked for me:

  • Start Visual Studio 2008 or later
  • Hit F1
  • Once the Help Document Explorer has come up, ensure the Index tab is selected in the left hand pane
  • Enter => in the Look for field
  • The first item in the list is now the help article you need.
0

精彩评论

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

关注公众号