How to have Lists with events upon change in List

2020-07-18 09:23发布

I'm a newbie in events. This example shows that an event is invoked every time the ArrayList is changed. I would like to know how to do it using generics. To you implement IList or extend List? I tried to code it but I'm stuck.

using System;
using System.Collections.Generic;

namespace Events
{
    public delegate void ChangedEventHandler(object sender, EventArgs e);

    public class ListWithChangedEvent<T> : IList<T>
    {
        public event ChangedEventHandler Changed;

        protected virtual void OnChanged(EventArgs e)
        {
            if (Changed != null)
            {
                Changed(this, e);
            }
        }

        public void Add(T value)
        {
            base.Add(value);
            OnChanged(EventArgs.Empty);
        }

        public void Clear()
        {
            base.Clear();
            OnChanged(EventArgs.Empty);
        }

        public T this[int index]
        {
            set
            {
                base[index] = value;
                OnChanged(EventArgs.Empty);
            }
        }
    }

    class EventListener
    {
        private ListWithChangedEvent<string> List;

        public EventListener(ListWithChangedEvent<string> list)
        {
            List = list;
            List.Changed += new ChangedEventHandler(ListChanged);
        }

        private void ListChanged(object sender, EventArgs e)
        {
            Console.WriteLine("This is called when the event fires.");
        }

        public void Detach()
        {
            List.Changed -= new ChangedEventHandler(ListChanged);
            List = null;
        }
    }

    class Program
    {
        public static void Main(string[] args)
        {
            ListWithChangedEvent<string> list = new ListWithChangedEvent<string>();

            EventListener listener = new EventListener(list);

            list.Add("item 1");
            list.Clear();
            listener.Detach();
        }
    }
}

1条回答
Evening l夕情丶
2楼-- · 2020-07-18 09:54

You can use ObservableCollection and you can extend it !!
Namespace: System.Collections.ObjectModel
Assembly: WindowsBase (in WindowsBase.dll)

This collection fires events whenever the list is changed.(say any items are added, removed from list)

But note : The ObservableCollection doesnt fire events if the internal properties of objects it is holding changes. If you need that do let me know, I have extended the Observable collection to have that feature also.

查看更多
登录 后发表回答