-
What do you people think about this solution to encapsulate a collection and be able to know when an iten is added/removed.
-
How can I add a clicable link to the xml description?
// 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); } }}
What do you people think about this solution to encapsulate a collection and be
Share
You can use
ObservableCollection<T>for this purpose. No need to write it yourself.Besides: When subclassing
Collection<T>it’s enough to override the protected virtual methods. All other public methods will invoke them.If you additionally hide the non-virtual ones the way you did, events might be triggered multiple times (and in your case, when clearing the collection, no event will be triggered).