我可以忽略与lambda语法委托参数? [英] Can I ignore delegate parameters with lambda syntax?

查看:152
本文介绍了我可以忽略与lambda语法委托参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,为什么C#让我忽略在某些情况下,委托的参数,而不是其他。

I am curious why C# allows me to ignore delegate parameters in some cases but not others.

例如,这是允许的:

Action<int> action = delegate { Console.WriteLine("delegate"); };



但这不是:

but this is not:

Action<int> action = () => Console.WriteLine("lambda");



有没有一种方法来初始化一个委托,并使用一个lambda忽略的参数?我知道我可以一个参数添加到Lambda和修复前行,但是这更多的是一个学术问题有关的编译器和为什么或如何工作的。

Is there a way to initialize a delegate and ignore the parameters using a lambda? I know that I can add a single parameter to the lambda and fix the previous line but this is more of an academic question pertaining to the compiler and why or how this works.

推荐答案

我相信,你的第一个样品实际上创建了一个匿名函数,能够承担许多不同的签名,其身体是单个语句 Console.WriteLine ... 。因为它可以搭配不同的签名,它不会导致出现问题。在第二个样本中,lambda语法本身定义的函数不带参数使用相同的身体。显然,这样你得到的错误,后者是不符合规定的一致行动。

I believe that your first sample actually creates an anonymous function that is able to take on many different signatures whose body is the single statement Console.WriteLine.... Because it can match different signatures, it does not cause a problem. In the second sample, the lambda syntax itself defines a function that takes no parameters with the same body. Obviously the latter is not consistent with the defined Action so you get the error.

C#匿名方法参考

有一个情况,其中的
匿名方法提供的lambda
表情没有发现
功能。匿名方法使
你省略参数列表,
,这意味着匿名方法
可以被转换成代表与
各种签名。这不是
可能的lambda表达式。

There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list, and this means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.

这篇关于我可以忽略与lambda语法委托参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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