> Func键℃之间的差异;与委托和lambda表达式 [英] Difference between Func<> with delegate and lambda expression
问题描述
同时加深自己的C#更先进的功能,我遇到了一些代码,但我并不确切知道的差异。这是关于两行:
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);
和
Func<string, int> giveLength = delegate(string text) { return text.Length; };
这可以用同样的方式使用:
This can be used in the same way:
Console.WriteLine(giveLength("A random string."));
所以基本上..什么是这两条线的区别?而且这些线路编译到同一CIL?
So basically.. What is the difference of these two lines? And are these lines compiling to the same CIL?
推荐答案
他们是一样的,基本上是这样。他们两个的匿名函数的在C#中规范的术语。
They're the same, basically. They're both anonymous functions in C# specification terminology.
Lambda表达式一般都比较简洁,也可以转换成的expression树的,这些都是进程外,LINQ是至关重要的。
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");
};
考虑如何很少需要对后一点,匿名方法正在成为现代的C#濒危物种。 Lambda表达式更为常见。
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键℃之间的差异;与委托和lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!