Expression Lambda versus Statement Lambda

前端 未结 8 855
北荒
北荒 2020-12-30 02:02

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

private delegate         


        
相关标签:
8条回答
  • 2020-12-30 02:35

    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;
    
    0 讨论(0)
  • 2020-12-30 02:43

    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.

    0 讨论(0)
提交回复
热议问题