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

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

问题描述

我很好奇为什么C#允许我在某些情况下忽略代理参数,但不能忽略其他参数。



例如这是允许的:

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

但这不是:

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

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

解决方案

我相信你的第一个样例实际上创建了一个匿名函数,可以承载许多不同的签名,其身体是单个语句 Console.WriteLine ... 。因为它可以匹配不同的签名,它不会造成问题。在第二个示例中,lambda语法本身定义了一个不带相同主体的参数的函数。显然,后者与定义的Action不符,所以你得到错误。



C#匿名方法参考


有一种情况下,
匿名方法提供
表达式中没有找到的
功能。匿名方法使
可以省略参数列表,而
这意味着匿名方法
可以转换为具有
各种签名的代理。这不是λb $ b可能与lambda表达式。



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

For instance this is permitted:

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

but this is not:

Action<int> action = () => Console.WriteLine("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.

解决方案

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# Anonymous Method Reference

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天全站免登陆