Why can anonymous delegates omit arguments, but la

2019-02-11 16:05发布

//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. :-/

2条回答
Root(大扎)
2楼-- · 2019-02-11 16:05

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?

查看更多
何必那么认真
3楼-- · 2019-02-11 16:09

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.
  • 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

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.
  • 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.

查看更多
登录 后发表回答