好的,所以我一直在寻找一个字典,当一条数据发生更改时会引发一个事件。我不断遇到的链接之一是:http: //blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx
检查 IDictionary 接口和 Dictionary 类后,我可以清楚地看到 CRUD(创建读取更新删除)。理论上所有的字典都应该建立在这个功能之上。
据我所知,实现可观察字典应该很简单
public class test<K,V> : Dictionary<K,V>, INotifyCollectionChanged, INotifyPropertyChanging
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public event PropertyChangedEventHandler PropertyChanged;
private const string pCount = "Count";
private const string pKeys = "Keys";
private const string pValues = "Values";
public V this[K key]
{
get
{
return base[key];
}
set
{
object old = base[key];
base[key] = value;
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, new KeyValuePair<K, V>(key, value), new KeyValuePair<K, V>(key, (V)old)));
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(pValues));
}
}
public override void Add(K key, V value)
{
base.Add(key, value);
if(CollectionChanged!=null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new KeyValuePair<K,V>(key, value)));
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pCount));
PropertyChanged(this, new PropertyChangedEventArgs(pKeys));
PropertyChanged(this, new PropertyChangedEventArgs(pValues));
}
}
public override void Remove(K key)
{
object removed = base[key];
base.Remove(key);
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, removed));
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(pCount));
PropertyChanged(this, new PropertyChangedEventArgs(pKeys));
PropertyChanged(this, new PropertyChangedEventArgs(pValues));
}
}
}
编辑:添加更多以使其更像示例并帮助澄清问题
我不明白为什么要制作所有这些精心制作的词典,有什么我遗漏的吗?有人可以向我解释一下吗?
感觉就像他们都在重新发明轮子,据我所知,这违背了面向对象的可重用代码。我真的觉得我一定是错过了什么。