我很好奇为什么 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"); };
但这不是:
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 语法本身定义了一个不接受具有相同主体的参数的函数.显然后者与定义的 Action 不一致,所以你会得到错误.
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 语法忽略委托参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!