Por que não há ObservableKeyedCollection<TKey, TValue> no .NET Framework?
-
24-09-2019 - |
Pergunta
O .NET Framework contém desde a versão 3.0 o ObservávelCollection<T>, mas por que não existe um ObservableKeyedCollection<TKey, TValue>.
Ok, eu poderia implementar minha própria coleção derivando de KeyedCollection<TKey,TValue> e implementando o INotifyCollectionChanged interface, mas não seria uma boa adição ao .NET Framework.
Solução
A razão pela qual não há observação ObservableCollection é genérico, e isso facilita a implementação de uma "Collection de observação", tão fácil quanto esta:
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 );
}
}
Embora esse certamente não seja um programa de uma linha, a maior parte é o Boilerplate. O mais importante, não reimplementar o ObservableCollection como você estava sugerindo; Em vez disso, ele utiliza totalmente.
A razão pela qual "não seria um bom complemento para a estrutura .NET" é porque quando já existe uma maneira de fazer algo, criar outra maneira de fazê -lo é uma má idéia. Quanto menos maneiras de realizar alguma tarefa específica, menos maneiras de fazê -lo mal. 8)
As ferramentas são fornecidas, agora é tudo sobre como você as usa.
Espero que ajude!
Outras dicas
Por favor, dê uma olhada no ObservableKeyEdCollection Classe Implementation. É muito fácil.
Eu recomendo que você dê uma olhada C5.É uma maravilhosa biblioteca de coleções genéricas que oferece coleções observáveis como padrão para todas as suas coleções, incluindo Added
, Inserted
, Removed
, RemovedAt
, Cleared
, e Changed
.Além disso, todas as coleções C5 defendem o ideal de “programação para interface”.Todas as interfaces fornecidas expõem a funcionalidade completa das implementações subjacentes - o que está faltando no System.Collections.Generic
espaço para nome.Além disso, há uma minuciosa documentação.Eu recomendo fortemente que você dê uma olhada.