Jeh*_*hof 8 .net .net-3.0 inotifycollectionchanged
.NET Framework自3.0版本开始包含ObservableCollection <T>,但为什么没有ObservableKeyedCollection <TKey,TValue>.
好吧,我可以通过从KeyedCollection <TKey,TValue>派生并实现INotifyCollectionChanged接口来实现我自己的集合,但它不是.NET Framework的一个很好的补充.
没有 ObservableKeyedCollection (或任何其他此类类型,只是其他泛型类型的组合)的原因是因为ObservableCollection是泛型的,这使得“ObservableKeyedCollection”的实现如此简单:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
public class DictionaryWatcher : ObservableCollection<KeyValuePair<string, object>>, IDisposable
{
private NotifyCollectionChangedEventHandler watcher;
private bool watching = false;
public DictionaryWatcher()
{
watcher = new NotifyCollectionChangedEventHandler( ReportChange );
CollectionChanged += watcher;
Watched = true;
}
public bool Watched
{
get
{
return watching;
}
set
{
if (watching)
{
lock (this)
{
CollectionChanged -= watcher;
watching = false;
}
}
}
}
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize( this );
}
public void Initialize()
{
this.Add( new KeyValuePair<string, object>( "First", 1 ) );
this.Add( new KeyValuePair<string, object>( "Second", 2 ) );
this.Add( new KeyValuePair<string, object>( "Turd", 3 ) );
KeyValuePair<string, object> badValue = this[2];
this.Remove( badValue );
}
protected virtual void Dispose( bool disposing )
{
if (disposing && Watched)
{
Watched = false;
}
}
private void ReportChange( object sender, NotifyCollectionChangedEventArgs e )
{
Console.WriteLine( "Change made: {0}", e.Action );
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这肯定不是一个简单的程序,但其中大部分都是样板文件。最重要的是,它没有像您建议的那样重新实现 ObservableCollection ;相反,它充分利用了它。
之所以说它“不是 .NET Framework 的一个好的补充”,是因为当已经有一种方法可以完成某件事时,创建另一种方法来完成某件事是一个坏主意。完成某项特定任务的方法越少,做得不好的方法就越少。8)
工具已经提供了,现在就看你如何使用它们了。
希望有帮助!