List firing Event on Change

前端 未结 5 696
说谎
说谎 2020-12-10 03:37

I created a Class EventList inheriting List which fires an Event each time something is Added, Inserted or Removed:

public          


        
5条回答
  •  旧时难觅i
    2020-12-10 03:44

    I have a Solution for when someone calls the Generic method from IList.add(object). So that you also get notified.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    
    namespace YourNamespace
    {
        public class ObjectDoesNotMatchTargetBaseTypeException : Exception
        {
            public ObjectDoesNotMatchTargetBaseTypeException(Type targetType, object actualObject)
                : base(string.Format("Expected base type ({0}) does not match actual objects type ({1}).",
                    targetType, actualObject.GetType()))
            {
            }
        }
    
        /// 
        /// Allows you to react, when items were added or removed to a generic List.
        /// 
        public abstract class NoisyList : List, IList
        {
            #region Public Methods
            /******************************************/
            int IList.Add(object item)
            {
                CheckTargetType(item);
                Add((TItemType)item);
                return Count - 1;
            }
    
            void IList.Remove(object item)
            {
                CheckTargetType(item);
                Remove((TItemType)item);
            }
    
            public new void Add(TItemType item)
            {
                base.Add(item);
                OnItemAdded(item);
            }
    
            public new bool Remove(TItemType item)
            {
                var result = base.Remove(item);
                OnItemRemoved(item);
                return result;
            }
            #endregion
    
            # region Private Methods
            /******************************************/
            private static void CheckTargetType(object item)
            {
                var targetType = typeof(TItemType);
                if (item.GetType().IsSubclassOf(targetType))
                    throw new ObjectDoesNotMatchTargetBaseTypeException(targetType, item);
            }
            #endregion
    
            #region Abstract Methods
            /******************************************/
            protected abstract void OnItemAdded(TItemType addedItem);
    
            protected abstract void OnItemRemoved(TItemType removedItem);
            #endregion
        }
    }
    

提交回复
热议问题