有一个一般的具体实现的KeyedCollection? [英] Is there a general concrete implementation of a KeyedCollection?

查看:924
本文介绍了有一个一般的具体实现的KeyedCollection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



框架设计指南书表示应为抽象类型提供具体实现 )。为什么框架设计师会抛弃这样一个有用的类的一个具体的实现,特别是当它可以通过简单地暴露一个构造函数来接受和存储 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);
}
}


解决方案

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




  • KeyedByTypeCollection< TItem> (我经常使用此类别)

  • MessageHeaderDescriptionCollection

  • ul>

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


    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):

    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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆