开发者

Lambda expression vs anonymous methods [duplicate]

This question already has answers here: delegate keyword vs. 开发者_如何学编程lambda notation (6 answers) Closed 9 years ago.

I would like to know what is the difference. Currently I am learning this stuff and it seems to me like these are just the same:

delegate void X();

X instanceOfX;

instanceOfX = delegate() { code };

instanceOfX = () => { code };

Also if the lambda are newer, should I just use lambda and forget on anonymous methods?


Yes, lambda expressions are just very special anonymous methods.

However, there are some deep differences. Start with Eric Lippert's Lambda Expression vs. Anonymous Methods, Part One and continue to the rest of the series.


The only difference is the lambda can be easily cast to Expression<Func<void>>. The delegates are purely just methods/closures, but the lambda can also be broken down into an expression tree:

Expression<Func<int, int>> expr = x => x*2; // Expression tree
Func<int, int> fun = x => x*2;              // Function
delegate int MyDelegate(int x);             // Delegate
MyDelegate del = x => x*2;                  // Same as Function and Delegate
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜