代码之家  ›  专栏  ›  技术社区  ›  Sprague

C事件和lambdas,是否替代空检查?

c#
  •  5
  • Sprague  · 技术社区  · 15 年前

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

    这里的目标是替代:

    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;
    

    }

    3 回复  |  直到 8 年前
        1
  •  3
  •   EgorBo    15 年前
    public event FooDelegate onFoo = delegate {};
    
        2
  •  5
  •   John Feminella    15 年前

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

    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());
    
        3
  •  0
  •   Glorfindel Doug L.    8 年前

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

    onFoo?.Invoke(this, null);
    

    (每当遇到此类代码时: if (onFoo != null) onFoo.Invoke(this, null) )

    该运营商于2015年发布了C 6.0。