我一直使用至今的方法是使从System.Collections.ObjectModel.Collection<T>
派生的私人收藏类,并直接在覆盖调用的方法:
class MyManagerClass
{
private class MyCollection : System.Collections.ObjectModel.Collection<object>
{
private MyManagerClass manager;
private MyCollection(MyManagerClass manager)
{
this.manager = manager;
}
protected override void InsertItem(int index, object item)
{
base.InsertItem(index, item);
manager.OnItemAddedToList(item);
}
protected override void SetItem(int index, object item)
{
object oldItem = (index < base.Count) ? base[index] : null;
base.SetItem(index, item);
if (oldItem != null) {
manager.OnItemRemovedFromList(oldItem);
}
manager.OnItemAddedToList(item);
}
protected override void RemoveItem(int index, object item)
{
base.RemoveItem(index, item);
manager.OnItemRemovedFromList(item);
}
}
private OnItemAddedToList(object o)
{
}
private OnItemRemovedFromList(object o)
{
}
}
我'不知道这是否是正确方式做到这一点,但我想看看是否有更好的选择。
冒泡事件正是我寻找这个功能的原因。 收藏与事件良好的做法?这个想法看起来很不舒服,因为它听起来像MS已经实施的东西,如果它在某种程度上不坏。 – 2008-12-16 12:47:19