简体   繁体   中英

C# delegate definition - anonymous methods vs. formally defined methods

何时应该在定义委托时使用匿名方法,何时应该在定义委托时使用正式定义的方法?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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