【问题标题】:Returning Dictionary as ICollection将字典作为 ICollection 返回
【发布时间】:2012-10-03 15:05:14
【问题描述】:

我有一个可以实现各种集合和数据类型的接口,它适用于某些集合,但字典给我带来了问题,我猜是因为字典有点不同并且有键值对?

public interface IStructure
{
    void InsertRun<T> (T item);
    ICollection RetrieveSortedListRun<T>();
    T RetrieveItemRun<T>(T item);
}

class DictionaryRun : IStructure
{
    IDictionary<int, object> dictionary;

    public DictionaryRun()
    {
        dictionary = new Dictionary<int, object>();
    }

    public void InsertRun<T>(T item)
    {
        dictionary.Add(dictionary.Count + 1, item);
    }

    public ICollection RetrieveSortedListRun<T>()
    {
        return dictionary;
    }

    public T RetrieveItemRun<T>(T item)
    {
        return item;
    }
}

【问题讨论】:

  • 好的...那么您是如何使用ICollection 的?目前您遇到了什么问题使其无法正常工作?

标签: c# generics collections dictionary icollection


【解决方案1】:

IDictionary&lt;TKey, TValue&gt; 没有实现ICollection,它实现了ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;。

照原样,如果您将字典更改为 IDictionary,您的代码将会编译。

但是,在我看来,您对界面和对象的整体设计可以重新设计。

public interface IStructure<T>
{
  void InsertRun(T item);
  ICollection<T> RetrieveSortedListRun();
  T RetrieveItemRun(T item);
}


class DictionaryRun<T> : IStructure<T>
{
  IDictionary<int, T> dictionary;

  public DictionaryRun()
  {
    dictionary = new Dictionary<int, T>();
  }

  public void InsertRun(T item)
  {
    dictionary.Add(dictionary.Count + 1, item);
  }

  public ICollection<T> RetrieveSortedListRun()
  {
    return dictionary.Values;
  }

  public T RetrieveItemRun(T item)
  {
    return item;
  }
}

【讨论】:

  • 似乎工作得很好,我在实现其他集合(如数组列表和哈希表)并尝试在 RetrieveSortedList 方法中返回它们时遇到问题。 arraylist 和 hashtable 是否没有实现 ICollection 而只是 ICollection?该程序的目的是衡量各种数据结构的效率。我应该稍微阅读一下如何一起使用不同的集合和接口。
  • @Kosmo ArrayList 和 Hashtable 只实现 ICollection,有像 List&lt;T&gt; 和 HashSet&lt;T&gt; 这样的类型选项,你可以看看哪个实现了 ICollection&lt;T&gt;。
【解决方案2】:

Dictionary&lt;TKey,TValue&gt; 实现 ICollection&lt;KeyValuePair&lt;TKey,TValue&gt;&gt; 而不是 ICollection&lt;TValue&gt;。似乎您从未使用过密钥,那么为什么不使用 HashSet&lt;T&gt; 呢? HashSet&lt;T&gt; 实现 ICollection&lt;T&gt;。


更新

你的代码行

dictionary.Add(dictionary.Count + 1, item);

让我认为您所需要的只是一个有序列表。与根据键对列表进行排序的排序列表相比,有序列表保持原始插入顺序。所以你最好使用List&lt;T&gt;。

【讨论】:

  • 我同意,如果您从不使用字典中的密钥,为什么还要使用字典。如果要允许重复使用 List,如果不想允许重复使用 HashSet
【解决方案3】:

是的,但是 Dictionary 有一个方法可以将自己转换为一个 List,它实现了 ICollection:

public ICollection RetrieveSortedListRun<T>()
{
    return dictionary.ToList();
}

这将返回KeyValuePairs 的集合。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
相关资源
最近更新 更多