什么时候显式使用 delegate 关键字而不是 lambda 是更好的做法?

发布于 2024-08-13 04:08:08 字数 362 浏览 4 评论 0原文

对于显式使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

美人迟暮 2024-08-20 04:08:08

Lambda 语法更加通用,设计者表示他们最好删除旧的重叠语法(没有引用,但可能是 Eric Lippert 或 Jon Skeet 在一本书或播客中)。

但是 delegate 允许您忽略参数,例如:

object.Event += delegate { };

与不得不说:

object.Event += (sender,args) => { };

这在大型参数列表中非常有用和/或使代码更容易重构。

编辑:正如 Yann Schwartz 在另一个答案中指出的那样(现在不幸被删除),这个技巧的一个非常巧妙的用法是为了使用空对象模式为事件提供默认处理程序:-(

class MyClassThatFiresWithoutTheTrick
{
    public event EventHandler MyEvent; // implicit = null

    // Need a method to keep this DRY as each fire requires a null check - see Framework Design Guidelines by Abrams and Cwalina
    protected virtual void OnMyEvent()
    {
        // need to take a copy to avoid race conditions with _removes
        // See CLR via C# 3rd edition p 264-5 for reason why this happens to work
        //var handler = MyEvent;
        // BUT THIS is the preferred version
        var handler = Interlocked.CompareExchange( ref MyEvent, null, null);
        // Need to do this check as it might not have been overridden
        if( handler == null)
            return;
        handler( this, EventArgs.Empty );
    }
}

class MyClassThatFiresWithTheTrick
{
    public event EventHandler MyEvent = delegate{};

    protected virtual void OnMyEvent()
    {
        MyEvent( this, EventArgs.Empty );
    }
}

尽管您可能经常最终做的是 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.:

object.Event += delegate { };

versus having to say:

object.Event += (sender,args) => { };

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:-

class MyClassThatFiresWithoutTheTrick
{
    public event EventHandler MyEvent; // implicit = null

    // Need a method to keep this DRY as each fire requires a null check - see Framework Design Guidelines by Abrams and Cwalina
    protected virtual void OnMyEvent()
    {
        // need to take a copy to avoid race conditions with _removes
        // See CLR via C# 3rd edition p 264-5 for reason why this happens to work
        //var handler = MyEvent;
        // BUT THIS is the preferred version
        var handler = Interlocked.CompareExchange( ref MyEvent, null, null);
        // Need to do this check as it might not have been overridden
        if( handler == null)
            return;
        handler( this, EventArgs.Empty );
    }
}

class MyClassThatFiresWithTheTrick
{
    public event EventHandler MyEvent = delegate{};

    protected virtual void OnMyEvent()
    {
        MyEvent( this, EventArgs.Empty );
    }
}

(though what you might often end up doing is an Inline Method of OnMyEvent, making the code even shorter again.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文