C#事件和Lambda,替代null检查?

Spr*_*gue 5 c#

有人看到任何缺点吗?应该注意的是,你不能从事件委托列表中删除匿名方法,我知道这一点(实际上这是概念上的动机).

这里的目标是替代:

if (onFoo != null) onFoo.Invoke(this, null);
Run Code Online (Sandbox Code Playgroud)

和代码:

public delegate void FooDelegate(object sender, EventArgs e);

public class EventTest
{
    public EventTest()
    {
        onFoo += (p,q) => { };
    }

    public FireFoo()
    {
         onFoo.Invoke(this, null);
    }

    public event FooDelegate onFoo;
Run Code Online (Sandbox Code Playgroud)

}

Joh*_*lla 5

另一种方法是改为使用扩展方法:

public static class EventExtensions {
    public static void Fire<T>(this EventHandler<EventArgs<T>> handler, object sender, T args) {
        if (handler != null)
            handler(sender, new EventArgs<T>(args));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在它只是:

TimeExpired.Fire(this, new EventArgs());
Run Code Online (Sandbox Code Playgroud)


Nag*_*agg 3

public event FooDelegate onFoo = delegate {};
Run Code Online (Sandbox Code Playgroud)