Func<>与委托和lambda表达式 [英] Difference between Func<> with delegate and lambda expression

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

问题描述

在深入自己的C#的更高级功能的同时,我遇到了一些代码,我不完全相同的区别。这是关于这两行:

  Func< string,int> giveLength =(text => text.Length); 

  Func< string,int> giveLength = delegate(string text){return text.Length; }; 

可以以相同的方式使用:

  Console.WriteLine(giveLength(A random string。)); 

所以基本上这两行有什么区别?这些线是否编译成相同的CIL?

解决方案

基本上是一样的。他们都是C#规范术语中的匿名函数



Lambda表达式通常更简洁,也可以转换为 表达式树 ,这对于进程外关键LINQ。



如果您不在意,匿名方法允许您删除参数列表。例如:

  EventHandler handler = delegate {
Console.WriteLine(发件人和参数无关紧要) ;
};

鉴于后一点的需求很少,匿名方法正在成为现代C#中的濒危物种。 Lambda表达式更常见。


while deepening myself to more advanced features of C#, I came across some code, which I didn't exactly know the difference of. It's about these two lines:

Func<string, int> giveLength = (text => text.Length);

and

Func<string, int> giveLength = delegate(string text) { return text.Length; };

This can be used in the same way:

Console.WriteLine(giveLength("A random string."));

So basically.. What is the difference of these two lines? And are these lines compiling to the same CIL?

解决方案

They're the same, basically. They're both anonymous functions in C# specification terminology.

Lambda expressions are generally more concise, and can also be converted to expression trees, which are crucial for out-of-process LINQ.

Anonymous methods allow you to drop the parameter list if you don't care. For example:

EventHandler handler = delegate { 
    Console.WriteLine("Sender and args don't matter");
};

Given how rarely the latter point is required, anonymous methods are becoming an endangered species in modern C#. Lambda expressions are much more common.

这篇关于Func&lt;&gt;与委托和lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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