有人看到任何缺点吗?应该注意的是,您不能从事件委托(delegate)列表中删除匿名方法,我知道这一点(实际上这是概念上的动机)。
这里的目标是替代:
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;
最佳答案
一种替代方法是创建一个扩展方法:
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));
}
}
现在只是:
TimeExpired.Fire(this, new EventArgs());
关于C# 事件和 Lambdas,空检查的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2877809/