Expression Lambda versus Statement Lambda

2019-02-06 04:24发布

Fundamentally, is there any difference between a single-line expression lambda and a statement lambda? Take the following code, for example:

private delegate void MyDelegate();

protected static void Main()
{
    MyDelegate myDelegate1 = () => Console.WriteLine("Test 1");
    MyDelegate myDelegate2 = () => { Console.WriteLine("Test 2"); };

    myDelegate1();
    myDelegate2();

    Console.ReadKey();
}

While I prefer the first because I find the brackets to be ugly, is there anything different between the two (besides the obvious part about requiring brackets for multi-line statements)?

标签: c# lambda
7条回答
Deceive 欺骗
2楼-- · 2019-02-06 04:38

The two are the same - the first is syntactic sugar to the second and both will compile to the same IL.

查看更多
老娘就宠你
3楼-- · 2019-02-06 04:40

Reflector to the rescue! The disassembled code looks like this:

private static void Main(string[] args)
{
    MyDelegate myDelegate1 = delegate {
        Console.WriteLine("Test 1");
    };
    MyDelegate myDelegate2 = delegate {
        Console.WriteLine("Test 2");
    };
    myDelegate1();
    myDelegate2();
    Console.ReadKey();
}

So no, there is no real difference between the two. Be happy.

查看更多
叛逆
4楼-- · 2019-02-06 04:41

No, there is no difference in this example. If the body of the lambda is only one expression, you can drop the brackets. However, once the lambda contains more than one expression, like so:

MyDelegate myDelegate2 = () => { 
  Console.WriteLine("Test 2");                      
  Console.WriteLine("Test 2"); 
};

the brackets are mandatory.

查看更多
对你真心纯属浪费
5楼-- · 2019-02-06 04:49

You need statement lambda for multistatement lambdas. In addition statement lambdas are not supported by expression providers like LINQ to SQL. Before .NET 4.0 the .NET Framework did not have support for statement expression trees. This was added in 4.0 but as far as I know no provider uses it.

Action myDelegate1 = () => Console.WriteLine("Test 1");
Expression<Action> myExpression = () => { Console.WriteLine("Test 2") }; //compile error unless you remove the { }
myDelegate1();
Action myDelegate2 = myExpression.Compile();
myDelegate2();

Otherwise they are the same.

查看更多
够拽才男人
6楼-- · 2019-02-06 04:50

If the delegate returns a value, return is necessary in statement lambda as follows.

        Func<int, int, bool> foo = (x, y) => { return x == y; };
        Func<int, int, bool> goo = (x, y) => x == y;
查看更多
别忘想泡老子
7楼-- · 2019-02-06 04:50

Personnaly, i prefer the Lambda Expression. The Expression have a value where the Statement does not.

i think the following links can help you :

http://lambda-the-ultimate.org/node/1044

查看更多
登录 后发表回答