为什么.NET Framework中没有ObservableKeyedCollection <TKey,TValue>?

Jeh*_*hof 8 .net .net-3.0 inotifycollectionchanged

.NET Framework自3.0版本开始包含ObservableCollection <T>,但为什么没有ObservableKeyedCollection <TKey,TValue>.

好吧,我可以通过从KeyedCollection <TKey,TValue>派生并实现INotifyCollectionChanged接口来实现我自己的集合,但它不是.NET Framework的一个很好的补充.

Tas*_*ask 2

没有 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)

工具已经提供了,现在就看你如何使用它们了。

希望有帮助!

  • KeyedCollection 中有很多可用的东西,但您的解决方案中没有。例如基于键的索引器,防止添加具有相同键的项目等。因此上面的代码可能是样板代码,但它肯定不完整。该框架为我们提供的工具不仅易于使用,而且实现完整...... (10认同)
  • 我同意杰伦的观点。这个答案不具备 KeyedCollection 的基本功能。我还想指出,如果 ObservableKeyedCollection 是由框架提供的,那么我们将有尽可能少的方法来做到这一点 -1 - 而不是每个人都创建自己的解决方案,其中许多解决方案都会像这个一样被破坏。 (3认同)