简体   繁体   English

为什么匿名委托可以省略参数,但lambdas不能?

[英]Why can anonymous delegates omit arguments, but lambdas can't?

//ok
Action<int> CallbackWithParam1 = delegate { };    

//error CS1593: Delegate 'System.Action<int>' does not take 0 arguments
Action<int> CallbackWithParam2 = () => { };   

Just wondered why the discrepancy really. 只是想知道为什么差异真的。 :-/ : - /

Jared is of course correct. 贾里德当然是对的。 To add a couple more details: 要添加更多详细信息:

  • Almost no one uses the "skip the parameter list" syntax. 几乎没有人使用“跳过参数列表”语法。
  • We have no scenario for lambdas that requires that feature. 我们没有lambda 需要该功能的场景。
  • The feature complicates type inference and overload resolution, and makes it more likely that both will fail. 该功能使类型推断和重载分辨率复杂化,并使两者都更有可能失败。
  • What syntax would you like for the feature? 您希望该功能使用什么语法? Action<int> c = => {}; ??? ??? I have no desire whatsoever to make => into a unary prefix operator. 我不希望将=>变成一元前缀运算符。

So on the one hand we have the list of pros: 所以一方面我们有专业人士的名单:

  • Lambdas gain consistency with an unnecessary C# 2.0 feature that hardly anyone knows about or uses -- a feature that frankly, we wish we'd never done in the first place Lambdas与不必要的任何人都知道或使用的不必要的C#2.0功能保持一致 - 坦率地说,我们希望我们从未在第一时间做过这个功能

and the cons: 和缺点:

  • implementation complicates already-complex type inference and overload resolution algorithms 实现使已经复杂的类型推断和重载决策算法复杂化
  • feature leads to more bug possibilities for users with no corresponding gain in representational power. 功能导致用户更多的bug可能性,代表功率没有相应的增益。
  • no obviously nice syntax 没有明显好的语法

If you were given that list of pros and cons, what would you do? 如果你被列出了利弊列表,你会做什么? I hope "implement the feature" would not be your choice; 我希望“实现功能”不是你的选择; it was not ours. 这不是我们的。

It's essentially as simple as they are different features with different sets of supported scenarios. 它基本上就像它们是具有不同支持方案集的不同特征一样简单。 It's almost like asking 这几乎就像问

Why can lambdas be expressions but delegates can only be blocks? 为什么lambda是表达式,但委托只能是块?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM