System.Collections.ObjectModel.KeyedCollection類是System.Collections.Generic.Dictionary的一個非常有用的替代方法,尤其是當關鍵數據是要存儲的對象的一部分或您希望能夠按順序枚舉項目時。不幸的是,這個類是抽象的,我無法在覈心.NET框架中找到一個通用的具體實現。是否有KeyedCollection的一般具體實現?
Framework Design 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);
}
}
什麼是「公共新布爾包含(TItem項目)」的方法? – HappyNomad 2014-03-10 21:09:30
看到第一個鏈接(它已經壞了,所以我切換到了backback機器) – 2014-03-15 11:42:42
更好地稱它爲TryGetItem。 – nawfal 2014-05-19 13:53:54