为什么没有ObservableKeyedCollection<TKey, TValue=""> 中。净框架?
-
24-09-2019 - |
题
。净框架包含以来3.0版本的 ObservableCollection<T>, 但为什么不是有一个ObservableKeyedCollection<TKey, TValue="">.
好吧我会实现我的自由集合来自 KeyedCollection<TKey,TValue> 和执行 INotifyCollectionChanged 接口,但是whouldnt这是一个很好的补充。净框架。
解决方案
原因是,没有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 );
}
}
虽然这肯定不是一个衬垫的程序,大多数这样板。最重要的是,它没有重新实现 ObservableCollection 因为你是建议;相反,它充分利用它。
原因,它"whouldn不是一个很好的补充。净框架"是因为当时已经有一个办法做到的事,创造另一个方法就是一个糟糕的想法。较少的方式有得到一些特定的完成任务,较少的方式有做到这一差。8)
该工具提供,现在是所有关于你如何使用它们。
希望这可以帮助!
其他提示
请看看 ObservableKeyedCollection级的执行情况.这是相当容易的。
我建议你看看 C5 。这是一个美妙的泛型集合库,提供可观察集合的标准对所有的收藏,包括Added
,Inserted
,Removed
,RemovedAt
,Cleared
和Changed
的。此外,C5集合所有信奉的“编程接口”的理想。所有接口提供暴露下面的实施方式中,这是缺乏的System.Collections.Generic
命名空间的全部功能。此外,没有彻底文档一>。我强烈建议你检查一下。