什么时候显式使用 delegate 关键字而不是 lambda 是更好的做法?
对于显式使用 delegate
关键字而不是使用 lambda 的编码风格,是否有任何最佳实践?
例如,
new Thread(() =>
{
// work item 1
// work item 2
}).Start();
new Thread(delegate()
{
// work item 1
// work item 2
}).Start();
我认为 lambda 看起来更好。如果 lambda 是更好的风格,那么除了它在 lambda 实现之前就已经存在这一事实之外,拥有 delegate
关键字还有什么意义呢?
Is there any best practice with respect to coding style with respect to explicit use of the delegate
keyword instead of using a lambda?
e.g.
new Thread(() =>
{
// work item 1
// work item 2
}).Start();
new Thread(delegate()
{
// work item 1
// work item 2
}).Start();
I think the lambda looks better. If the lambda is better style, what's the point of having a delegate
keyword, other than for the fact that it existed before lambdas were implemented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Lambda 语法更加通用,设计者表示他们最好删除旧的重叠语法(没有引用,但可能是 Eric Lippert 或 Jon Skeet 在一本书或播客中)。
但是
delegate
允许您忽略参数,例如:与不得不说:
这在大型参数列表中非常有用和/或使代码更容易重构。
编辑:正如 Yann Schwartz 在另一个答案中指出的那样(现在不幸被删除),这个技巧的一个非常巧妙的用法是为了使用空对象模式为事件提供默认处理程序:-(
尽管您可能经常最终做的是
OnMyEvent
的内联方法,使代码再次变得更短。)Lambda syntax is much more generalised, and the designers have said that they'd ideally remove the old overlapping syntaxes (dont have a citation, but it's probably Eric Lippert or Jon Skeet in a book or a podcast).
But
delegate
allows you to ignore parameters, e.g.:versus having to say:
which can be very useful in large argument lists and/or to make the code more resilient to refactoring.
EDIT: As pointed out by Yann Schwartz in another answer (now unfortunately deleted), a very neat usage of this trick is in order to provide a default hander for an event using the Null Object pattern:-
(though what you might often end up doing is an Inline Method of
OnMyEvent
, making the code even shorter again.)