Why is Action/Func better than a regular Method in .Net?

前端 未结 5 453
滥情空心
滥情空心 2020-12-28 19:28

I much prefer using an Action or a Func if I need a quick reusable piece of code, however others on my team don\'t like them or understand them.
At the moment my only re

5条回答
  •  死守一世寂寞
    2020-12-28 19:34

    There are two sides to your question: style and performance.

    For code style, using delegates makes things a little messy. There is no function name associated with the body of code (anonymous method), argument types are inferred, and when overused this can lead to large function blocks containing lots of smaller independent chunks of code in delegates. It's not pretty to look at, it can be hard to figure out what the code is actually doing, and it's hard to find what you're looking for.

    For performance, delegates introduce an indirection that is not as fast to execute as a plain old method. The difference is small, but when used to excess it could become noticeable.

    Any tool has appropriate and excessive uses. It's appropriate to use Action or Func for a callback parameter when you want to pass a callback routine into a function. Using Action or Func as a replacement for declaring functions in general is a misuse, IMO.

提交回复
热议问题