表达式Lambda与语句Lambda [英] Expression Lambda versus Statement Lambda

查看:88
本文介绍了表达式Lambda与语句Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从根本上讲,单行表达式lambda和语句lambda之间有什么区别吗?以下面的代码为例:

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)?

推荐答案

对于多语句lambda,您需要使用语句lambda.另外,表达式提供程序(如LINQ to SQL)不支持语句lambda.在.NET 4.0之前,.NET Framework不支持语句表达式树.它是在4.0中添加的,但据我所知,没有提供者使用它.

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();

否则它们是相同的.

这篇关于表达式Lambda与语句Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆