Delegates, Lambdas, Action, Func, Anonymous Functi

2019-02-10 19:31发布

I just want to verify my understanding about the following

  • Delegate - a method signature
  • Lambdas - anonymous function
  • Anonymous Function - just that
  • Action - An anonymous function that returns nothing
  • Func - An anonymous function that returns something

hmm... they all do similar things, how do you define & know when to use each?

sorry, I don't explain well

3条回答
Emotional °昔
2楼-- · 2019-02-10 20:18
  • Delegate - it is not a method signature. It is a type which encapsulates a method. Hence a delegate declaration should have a signature similar to the method it wants to encapsulate. When to use Delegate - whenever you want to pass a method to another function. For more see this and this.

  • Lambdas - short hand and more expressive way of writing an anonymous function. But there is more to it. A lambda expression can also be converted to an expression tree. For more see this.

  • Anonymous Function - yes .. just that

  • Action - It is a delegate which can encapsulate a function that returns nothing. So you should think of it as a type that can encapsulate an action and use it when you need to pass an action around.

  • Func - A delegate that can encapsulate a function that returns something. But you should look at it as a type that can encapsulate a transformation and use when you want to pass around a transformation.

查看更多
The star\"
3楼-- · 2019-02-10 20:26

Don't try to see C# + these features. Also because there is not a strict pragmatic answer to your question.

Start from a functional programming point of view, for example try to learn F# to get inside what and when lambdas are used (actually everywhere inside a functional language) and then you'll understand things better.

It will open your mind and make you think differently about imperative programming or mixed languages like C#.

查看更多
Anthone
4楼-- · 2019-02-10 20:29

Action and Func are just special cases of the Delegate. Delegate itself is something that references a method and can be used to call it.

查看更多
登录 后发表回答