7

Here's my strategy for choosing which C# collection type to use:

  • if number of items in collection is fixed, then use an array, e.g.:

    string[] directions = new string[] { "north", "south", "east", "west" };

  • otherwise always use List<T>

  • unless of course you need a more specialized collection, e.g. Stack<T>, Queue<T>, or Dictionary<TKey, TValue>

  • but never use ArrayList anymore

Based on your experience, what is missing from this strategy?

4

3 回答 3

7

你的规则运作良好。

此外:

  • 始终优先使用泛型(或专用)集合而不是非泛型(object基于 - 的)集合。
  • 如果HashSet<T>您想检查是否存在而不是键值映射(通过 表示Dictionary),请使用。
  • 对于字典,如果排序看起来很重要,请考虑使用有序映射 ( SortedList<...>, )。SortedDictionary<...>
  • 如果中间有删除/插入操作,请使用链表。

当然还有最重要的一个:

  • 永远不要导出具体的集合类型:始终使用最通用的接口,即 - 在大多数情况下 -IList<T>IEnumerable<T>.
于 2010-08-08T20:22:31.290 回答
5

I'd say that in the majority of cases, even if I knew the number of items in a collection, I'd use List, simply for the number of utility functions it provides and compatibility with LINQ.

Hashmaps are an important use case, for when you would want faster access to items within the collection.

于 2010-08-08T20:19:21.413 回答
1

如果您计划在继承的类中覆盖添加/删除/清除方法,您也可以使用Collection<T>,因为存在虚拟方法。

于 2010-08-09T07:11:59.040 回答