How to handle add to list event?

后端 未结 10 2390
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 22:55

I have a list like this:

List list = new List

How to handle adding new position to this list?

When

10条回答
  •  悲哀的现实
    2020-11-29 23:26

    You could inherit from List and add your own handler, something like

    using System;
    using System.Collections.Generic;
    
    namespace test
    {
        class Program
        {
    
            class MyList : List
            {
    
                public event EventHandler OnAdd;
    
                public new void Add(T item) // "new" to avoid compiler-warnings, because we're hiding a method from base-class
                {
                    if (null != OnAdd)
                    {
                        OnAdd(this, null);
                    }
                    base.Add(item);
                }
            }
    
            static void Main(string[] args)
            {
                MyList l = new MyList();
                l.OnAdd += new EventHandler(l_OnAdd);
                l.Add(1);
            }
    
            static void l_OnAdd(object sender, EventArgs e)
            {
                Console.WriteLine("Element added...");
            }
        }
    }
    

    Warning

    1. Be aware that you have to re-implement all methods which add objects to your list. AddRange() will not fire this event, in this implementation.

    2. We did not overload the method. We hid the original one. If you Add() an object while this class is boxed in List, the event will not be fired!

    MyList l = new MyList();
    l.OnAdd += new EventHandler(l_OnAdd);
    l.Add(1); // Will work
    
    List baseList = l;
    baseList.Add(2); // Will NOT work!!!
    

提交回复
热议问题