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

时间:2009-12-02 10:53:24

标签: c# c#-3.0 delegates lambda

关于明确使用delegate关键字而不是使用lambda,是否有关于编码风格的最佳做法?

e.g。

new Thread(() =>
{
    // work item 1
    // work item 2
}).Start();

new Thread(delegate()
{
    // work item 1
    // work item 2
}).Start();

我认为lambda看起来更好。如果lambda是更好的样式,那么拥有delegate关键字的重点是什么,除了在lambdas实现之前它存在的事实?

1 个答案:

答案 0 :(得分:4)

Lambda语法更加通用,并且设计师已经说过他们理想地删除旧的重叠语法(没有引用,但可能是Eric Lippert或Jon Skeet在一本书或播客中)。

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

object.Event += delegate { };

与不得不说:

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

在大型参数列表中非常有用和/或使代码对重构更具弹性。

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

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的内联方法,使代码再次缩短。)