用于获取Collection的添加/删除事件的泛型类

Ped*_*o77 1 c# collections encapsulation

  1. 你怎么看待这个封装集合的解决方案,并且能够知道何时添加/删除它.

  2. 如何在xml描述中添加clicable链接?

    // Why does DoNotExposeGenericLists recommend that I expose Collection instead of List? by David Kean"
    // http://blogs.msdn.com/b/codeanalysis/archive/2006/04/27/585476.aspx
    public class CollectionEx<T> : Collection<T>
    {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;
    
    public CollectionEx()//:base()
    {
    }
    
    protected override void InsertItem(int index, T item)
    {
        base.InsertItem(index, item);
        OnSectionAdded(EventArgs.Empty);
    }
    
    protected override void RemoveItem(int index)
    {
        base.RemoveItem(index);
        OnSectionRemoved(EventArgs.Empty);
    }
    
    public new void Add(T item)
    {
        base.Add(item);
        OnSectionAdded(EventArgs.Empty);
    }
    public new bool Remove(T item)
    {
        bool ok = base.Remove(item);
        OnSectionRemoved(EventArgs.Empty);
        return ok;
    }
    
    protected override void ClearItems()
    {
        base.ClearItems();
    }
    
    protected virtual void OnSectionRemoved(EventArgs e)
    {
        EventHandler handler = this.ItemRemoved;
        if (handler != null)
        {
            handler(this, e);
        }
    }
    
    protected virtual void OnSectionAdded(EventArgs e)
    {
        EventHandler handler = this.ItemAdded;
        if (handler != null)
        {
            handler(this, e);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

    }

Mat*_*ias 8

你可以用它ObservableCollection<T>来达到这个目的.不需要自己写.

此外:当子类化Collection<T>它足以覆盖受保护的虚拟方法.所有其他公共方法都将调用它们.
如果您按照自己的方式另外隐藏非虚拟事件,则可能会多次触发事件(在您的情况下,清除集合时,不会触发任何事件).

  • 我认为在撰写博客文章时(2006年4月),没有"ObservableCollection" - 它与.NET 3.0一起发布(2006年11月);-) (2认同)