lambda表达式的语法VS LambdaExpression类 [英] lambda expression syntax vs LambdaExpression class

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

问题描述

这行代码试图将lambda表达式分配给 LambaExpression 类型的变量,

This line of code that tries to assign a lambda expression to a LambaExpression typed variable,

LambdaExpression expr = n => n;



它失败,编译错误消息:

it fails with compile error message:

无法转换拉姆达
表达键入
'System.Linq.Expressions.LambdaExpression'
,因为它不是一个委托

Cannot convert lambda expression to type 'System.Linq.Expressions.LambdaExpression' because it is not a delegate type

因此,它必须是一个委托类型。概念上,它似乎很奇怪我,因为我可以用一个工厂方法,像这样营造出一个 LambdaExpression 实例。

So it needs to be a delegate type. Conceptually it seems odd to me because I can build out a LambdaExpression instance using a factory method like so.

厂从MSDN LAMBDA

Factory Lambda from MSDN

LambdaExpression lambdaExpr = Expression.Lambda(
    Expression.Add(
        paramExpr,
        Expression.Constant(1)
    ),
    new List<ParameterExpression>() { paramExpr }
);



这不是一个委托类型。

and that's not a delegate type.

这让我们想知道为什么lambda来LambaExpression不能工作?

推荐答案

那么,这个的确实的工作:

Expression<Func<int, int>> exp = n => n;
LambdaExpression lambda = exp;



注意的 表达式来; TDelegate方式> LambdaExpression

我觉得你不能只使用其原因 LambdaExpression 作为类型是那么的N型(在你的例子)不能推断

I think the reason you can't just use LambdaExpression as the type is that then the type of n (in your example) could not be inferred.

考虑的事实,你也不能做到这一点,基本上是一样的道理。:

Consider the fact that you also can't do this, for basically the same reason:

// What is this? An Action? A ThreadStart? What?
Delegate d = () => Console.WriteLine("Hi!");



而你的可以的做到这一点:

Action a = () => Console.WriteLine("Hi!");
Delegate d = a;



这是本质上是一回事。

It's essentially the same thing.

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

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