C# delegate definition - anonymous methods vs. for

2019-05-09 02:55发布

问题:

When should anonymous methods be used when defining a delegate and when should formally defined methods be used when defining a delegate ?

回答1:

If you need to use the same logic in more than one place, it makes sense to use a separate method.

If you only need to use the logic once and it's fairly short, it makes sense to use an anonymous function. If the delegate needs access to local variables in the method which is creating it, anonymous functions act as closures which can also be very handy.

Additionally, an anonymous function can be useful even if it's reasonably long if it's used for something like parallelization with Parallel Extensions - part of the point of that is that you can take existing serial code and parallelise it "in place" to a large extent.

You might also want to consider testability - if your delegate's code is sufficiently complicated that it warrants its own unit tests, exposing it as a method makes a lot of sense. (Unfortunately it would have to be either an internal method using InternalsVisibleTo or a public method, where often you'd normally want it to be private, but such is life.)



回答2:

I use anonymous methods when the function that should be executed, should only be executed by that delegate (in other words: when I do not need that function in any other place), and, when the function/method that has to be executed is relatively short (5 lines max.).

But, there are no strict rules defined when to use what.
IMHO, I find that anonymous methods do not contribute to readability in most of the situations, so I mostly do not use them.