zoukankan      html  css  js  c++  java
  • 让集合支持事件

                                            让集合支持事件
                                                      电子科技大学软件学院03级02班 周银辉

        不明白为什么集合没有事件(除了几个特殊的集合:比如AutoCompleteStringCollection 类), 要是集合改变时,比如有元素被添加到集合时,集合能通过事件来通知我们该多好啊. 我们来改造集合.

    1, 看看CollcetionBase类

        CollectionBase.PNG
        注意到Insert方法中的this.OnInsert(index, value)和this.OnInsertComplete(index, value)方法, 这很让人很容易联想到引发事件的On*方法. 那么很简单地, 如果我们将this.OnInsert(index, value)重写为如下形式: 
    protected override void OnInsert(int index, object value)
            
    {
                
    base.OnInsert(index, value);
                
    this.OnElementInserting(new CollectionChangeEventArgs(CollectionChangeAction.Add, value));
            }
    其中的OnElementInserting如下:
     protected virtual void OnElementInserting(CollectionChangeEventArgs arg)
            
    {
                
    if (this.ElementInserting != null)
                
    {
                    
    this.ElementInserting(this, arg);
                }

            }
    而ElementInserting则恰好是我们定义的插入事件
    public event EventHandler<CollectionChangeEventArgs> ElementInserting;

    这样当有元素插入到集合时则会引发我们的ElementInserting事件

    2, 完整的代码(这里只演示了插入元素时的相关事件, 其他事件同理)

    CollectionWithEvents.cs

    Main.cs

    运行结果:
    CollectionWithEventsDemo.PNG

    3, Demo下载 https://files.cnblogs.com/zhouyinhui/CollcetionWithEventsDemo.rar
  • 相关阅读:
    快速实现一个带后端服务的 Vue 项目,用云开发Vue插件!
    做好内容安全检测,和风险说「再见」(下)!
    新能力|云调用支持微信支付啦!
    获奖结果公布|2020腾讯犀牛鸟云开发校园技术布道师养成计划
    SpringMVC原理及流程解析
    Mysql梳理-关于索引/引擎与锁
    写在庚子年之前
    Spring的BeanPostProcessor后置处理器与bean的生命周期
    AQS系列(六)- Semaphore的使用及原理
    AQS系列(五)- CountDownLatch的使用及原理
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/620980.html
Copyright © 2011-2022 走看看