你们如何看待这种封装集合并能够知道何时添加/删除项目的解决方案。
如何向 xml 描述添加可点击的链接?
// 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); } }
请您参考如下方法:
您可以使用 ObservableCollection<T> 以此目的。无需自己编写。
此外:子类化时 Collection<T>足以覆盖 protected 虚拟方法。所有其他公共(public)方法将调用它们。
如果您按照您的方式另外隐藏非虚拟的,事件可能会被触发多次(在您的情况下,当清除集合时,不会触发任何事件)。
