さて、データが変更されたときにイベントをスローする辞書を探していました。私が遭遇し続けたリンクの 1 つは次のとおりです。
IDictionary インターフェイスと Dictionary クラスを調べたところ、CRUD (create read update delete) がはっきりとわかります。理論上のすべての辞書は、この機能に基づいて構築する必要があります。
私が見る限り、観察可能な辞書の実装は次のように簡単なはずです
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));
}
}
}
編集:サンプルのようにし、質問を明確にするためにさらに追加しました
なぜこんなに手の込んだ辞書が作られているのか理解できません。何か足りないものはありますか? 誰かが私にこれを説明してもらえますか?
私が見る限り、オブジェクト指向のポイントである再利用可能なコードに反する車輪をすべて再発明しているように感じます。私は本当に何かが欠けているに違いないと感じています。