问题描述
的System.Collections.ObjectModel.KeyedCollection类是一个非常有用的替代System.Collections.Generic.Dictionary,特别是当关键数据是对象的一部分被存储或要能够枚举在订单中的项目。不幸的是,类是抽象的,我无法找到核心.NET框架一般的具体实现。
href="http://rads.stackoverflow.com/amzn/click/0321545613">框架设计Guidlines 书表明一个具体实施的应的提供的从项目到它的密钥转换:
公共类ConcreteKeyedCollection< TKEY的,TItem> :KeyedCollection< TKEY的,TItem>
{
私人器< TItem,TKEY的> getKeyForItem = NULL;
公共ConcreteKeyedCollection(转换器和LT; TItem,TKEY的> getKeyForItem)
{
如果(getKeyForItem == NULL){抛出新ArgumentNullException(getKeyForItem); }
this.getKeyForItem = getKeyForItem;
}
保护覆盖TKEY的GetKeyForItem(TItem项)
{
返回this.getKeyForItem(项目);
}
}
有具体的实现,包括(但不限于):
- KeyedByTypeCollection< TItem> (我经常使用这个类)
- MessageHeaderDescriptionCollection
要你的问题的精神,没有就没有通用的实施和因为我对微软不工作,我只能猜测。由于具体的实施是因为你已经证明是容易的,我不会提供任何猜测(因为它很可能是错的)。
The System.Collections.ObjectModel.KeyedCollection class is a very useful alternative to System.Collections.Generic.Dictionary, especially when the key data is part of the object being stored or you want to be able to enumerate the items in order. Unfortunately, the class is abstract, and I am unable to find a general concrete implementation in the core .NET framework.
The Framework Design Guidlines book indicates that a concrete implementation should be provided for abstract types (section 4.4 Abstract Class Design). Why would the framework designers leave out a general concrete implementation of such a useful class, especially when it could be provided by simply exposing a constructor that accepts and stores a Converter from the item to its key:
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);
}
}
There are concrete implementations, including (but not limited to):
- KeyedByTypeCollection<TItem> (I use this class frequently)
- MessageHeaderDescriptionCollection
To the spirit of your question, no there is no generic implementation and since I do not work for Microsoft I could only speculate. Since the concrete implementation is as easy as you've shown, I won't offer any speculation (as it would probably be wrong).
这篇关于是否有一个通用的具体实施KeyedCollection的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!