C# delegate definition - anonymous methods vs. for

2019-05-09 03:26发布

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

2条回答
\"骚年 ilove
2楼-- · 2019-05-09 03:40

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

查看更多
仙女界的扛把子
3楼-- · 2019-05-09 03:54

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.

查看更多
登录 后发表回答