C#委托定义 - 匿名方法与正式定义的方法 [英] C# delegate definition - anonymous methods vs. formally defined methods
问题描述
如果您需要在多个地方使用相同的逻辑,则使用单独的方法是有意义的。
如果您只需要使用逻辑一次和相当短,使用匿名函数是有意义的。如果委托需要在创建它的方法中访问局部变量,匿名函数将作为闭包,这也可以非常方便。
另外,匿名函数可以是如果它适用于与Parallel Extensions并行化的功能相当长的时间,那么即使可以使用现有的序列号,并在很大程度上将其并行并行,这一点很有用。
您可能还想考虑可测试性 - 如果您的委托代码足够复杂,以保证自己的单元测试,将其作为一种方法使其变得非常有意义。 (不幸的是,它必须是使用 InternalsVisibleTo
或公共方法的内部方法,通常你通常会希望它是私有的,但这是生活。) / p>
When should anonymous methods be used when defining a delegate and when should formally defined methods be used when defining a delegate ?
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.)
这篇关于C#委托定义 - 匿名方法与正式定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!