开发者

lambda expression syntax vs LambdaExpression class

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:

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

So it needs to be a delegate type. Conceptually it see开发者_StackOverflow中文版ms odd to me because I can build out a LambdaExpression instance using a factory method like so.

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.

It makes we wonder why lambda to LambaExpression cannot work?


Well, this does work:

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

Note that Expression<TDelegate> derives from LambdaExpression.

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!");

Whereas you can do this:

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

It's essentially the same thing.


Because LambdaExpression is a way to generate lambda expressions at runtime, where as n => n gets converted to a generated class at compile time.

In short: they are two different things to do the same thing, but can't be used together.


To quote MSDN The LambdaExpression type represents a lambda expression in the form of an expression tree. The Expression type, which derives from LambdaExpression and captures the type of the lambda expression more explicitly, can also be used to represent a lambda expression. At runtime, an expression tree node that represents a lambda expression is always of type Expression.

The value of the NodeType property of a LambdaExpression is Lambda.

Use the Lambda factory methods to create a LambdaExpression object.


Read carefully what errror message is saying. LambdaExpression is not a delegate. It is normal class. Read http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.aspx. Because it has Lambda in name doesn't mean it is same as 'true' lambda.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜