gpt4 book ai didi

.net - KeyedCollection 是否有一般的具体实现?

转载 作者:行者123 更新时间:2023-12-03 22:32:11 25 4
gpt4 key购买 nike

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

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);
}
}

最佳答案

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

  • KeyedByTypeCollection<TItem> (我经常使用这个类)
  • MessageHeaderDescriptionCollection

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

    关于.net - KeyedCollection 是否有一般的具体实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1842652/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com