开发者

Implement an event for a change in a SortedList

I'm hoping the answer is as simple as the question, but I need to write an event for a class that implements a SortedList.

Is there a way I can create an event handler for anytime this list changes (A开发者_如何转开发dd, Modify, Remove)? The Add() methods and such are not override-able.

Thanks!


No there is not. The best way to get this kind of behavior is to create a new class which wraps a SortedList<T>, exposes a similar set of methods and has corresponding events for the methods you care about.

public class MySortedList<T> : IList<T> {
  private SortedList<T> _list = new SortedList<T>();
  public event EventHandler Added;
  public void Add(T value) {
    _list.Add(value);
    if ( null != Added ) {
      Added(this, EventArgs.Empty);
    }
  }
  // IList<T> implementation omitted
}


Instead of inheriting from SortedList, you should encapsulate it. Make your class implement the same interfaces, in addition to INotifyCollectionChanged:

public class MySortedList<TKey, TValue> : IDictionary<TKey, TValue>, 
    ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, 
    IDictionary, ICollection, IEnumerable, INotifyCollectionChanged
{
    private SortedList<TKey, TValue> internalList = new SortedList<TKey, TValue>();

    public void Add(TKey key, TValue value)
    {
        this.internalList.Add(key,value);
        // Do your change tracking
    }
    // ... implement other methods, just passing to internalList, plus adding your logic
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜