2010-05-20 53 views
5

有没有人看到任何缺点?应该指出,你不能从一个事件委托列表中删除匿名方法,我意识到这一点(实际上这是这个概念的动机)。C#事件和Lambdas,替代空检查?

这里的目标是替代:

if (onFoo != null) onFoo.Invoke(this, null); 

,代码:

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; 

}

+0

好释放,你问我是不是要问,所以我不会。 – 2010-05-20 21:03:02

+0

没有重大的缺点。也没有什么好处。 – Jay 2010-05-20 21:08:33

回答

3
public event FooDelegate onFoo = delegate {}; 
+0

我不确定你想说什么。也许“代表(p,q){};”?该委托需要两个参数。 – Sprague 2010-05-20 21:08:35

+0

通过此事件初始化,您可以在不检查null的情况下触发事件。不,只是委托{}。 – Nagg 2010-05-20 21:10:45

+0

如果它能正常工作,那么我会投这个答案,明天早上测试它。 – Sprague 2010-05-20 21:15:59

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)); 
    } 
} 

现在它是绝对的T:

TimeExpired.Fire(this, new EventArgs()); 
0

的Visual Studio 的最新版本自动建议使用null-conditional operator

onFoo?.Invoke(this, null); 

(每当遇到这样的代码:if (onFoo != null) onFoo.Invoke(this, null))。

该运营商成为可与C#6.0在2015年