C# 在SortedList中执行更改事件
我希望答案和问题一样简单,但我需要为实现SortedList的类编写一个事件 是否有一种方法可以为该列表的任何更改(添加、修改、删除)创建事件处理程序?Add()方法等不可重写C# 在SortedList中执行更改事件,c#,events,event-handling,C#,Events,Event Handling,我希望答案和问题一样简单,但我需要为实现SortedList的类编写一个事件 是否有一种方法可以为该列表的任何更改(添加、修改、删除)创建事件处理程序?Add()方法等不可重写 谢谢 没有。获得此类行为的最佳方法是创建一个新类,该类封装了一个SortedList,公开了一组类似的方法,并为您关心的方法创建了相应的事件 public class MySortedList<T> : IList<T> { private SortedList<T> _list
谢谢 没有。获得此类行为的最佳方法是创建一个新类,该类封装了一个
SortedList
,公开了一组类似的方法,并为您关心的方法创建了相应的事件
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
}
公共类MySortedList:IList{
私有分类列表_list=新分类列表();
添加了公共事件事件处理程序;
公共无效添加(T值){
_列表。添加(值);
如果(空!=已添加){
添加(此为EventArgs.Empty);
}
}
//省略IList实现
}
您应该封装它,而不是从SortedList继承。除了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
}
公共类MySortedList:IDictionary,
i集合,i可数,
IDictionary、ICollection、IEnumerable、iNotifyCollection已更改
{
private SortedList internalList=新建SortedList();
公共无效添加(TKey键,TValue值)
{
this.internalList.Add(key,value);
//你的变化跟踪吗
}
//…实现其他方法,只需传递到internalList,再加上添加逻辑
}
使用现有接口可能更好,即:INotifyCollectionChanged@Reed,视情况而定。但是如果OP想要修改事件,那么INotifyCollectionChanged可能是另一个应该在ethat上实现的事件。