是否存在KeyedCollection的一般具体实现?

Kev*_*ler 14 .net collections

System.Collections.ObjectModel.KeyedCollection类是一个非常有用的替代System.Collections.Generic.Dictionary,尤其是当关键数据是存储对象的一部分,或者您希望能够枚举顺序的项目.不幸的是,这个类是抽象的,我无法在核心.NET框架中找到一般的具体实现.

框架的设计Guidlines书表明,一个具体的实现为抽象类型(第4.4节抽象类设计)来提供.为什么框架设计者会忽略这样一个有用的类的一般具体实现,特别是当它可以通过简单地暴露一个接受并将Converter从项目存储到其键的构造函数来提供时:

public class ConcreteKeyedCollection<TKey, TItem> : KeyedCollection<TKey, TItem>
{
    private Converter<TItem, TKey> getKeyForItem = null;
    public ConcreteKeyedCollection(Converter<TItem, TKey> getKeyForItem)
    {
        if (getKeyForItem == null) { throw new ArgumentNullException("getKeyForItem"); }
        this.getKeyForItem = getKeyForItem;
    }
    protected override TKey GetKeyForItem(TItem item)
    {
        return this.getKeyForItem(item);
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*116 8

有具体的实现,包括(但不限于):

对于你的问题的精神,没有没有通用的实现,因为我不为微软工作,我只能推测.由于具体实现就像你所展示的一样简单,我不会提出任何猜测(因为它可能是错误的).