Func 之间的区别使用委托和 lambda 表达式

Difference between Funclt;gt; with delegate and lambda expression(Func 之间的区别使用委托和 lambda 表达式)
本文介绍了Func 之间的区别使用委托和 lambda 表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在深入了解 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; };

这可以用同样的方式:

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 表达式一般比较简洁,也可以转换成表达式树,这对于进程外 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 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to pass lambda #39;include#39; with multiple levels in Entity Framework Core?(如何在 Entity Framework Core 中传递具有多个级别的 lambda include?)
Join/Where with LINQ and Lambda(使用 LINQ 和 Lambda 加入/在哪里)
Getting all types that implement an interface(获取所有实现接口的类型)
Combining two expressions (Expressionlt;Funclt;T, boolgt;gt;)(组合两个表达式 (ExpressionFuncT, boolgt;))
Is there a reason for C##39;s reuse of the variable in a foreach?(C# 在 foreach 中重用变量是否有原因?)
Lambda/Linq with Contains criteria for multiple keywords(Lambda/LINQ WITH包含多个关键字的条件)