这是更好地使用数组或列表&LT;&GT;? [英] Which is better to use array or List<>?
问题描述
我想知道哪种类型将有更好的表现,哪些你认为应该使用。
I was wondering which type would have better performance and which you think should be used.
例如我有一个字符串列表不知道我怎么会许多项目需要那么具有。新增(字符串)功能真的很方便。我可以在任何时候轻松地添加新的字符串到列表中。
For example I have a List of strings not knowing how many items I will need so having the .Add(String) function is really convenient. I can Add new strings to the list at any time easily.
有什么优势/使用每个缺点是什么?
What are the advantages/disadvantages of using each?
是列出了新的阵列?
推荐答案
更多情况下确实需要正确地回答这个问题:
More context is really required to answer the question properly:
在公开API ,你应该尝试使用抽象的集合类型,这样就可以在以后改变内部实现,如果你需要。
In a public API, you should try to use abstract collection types, so that you can change the internal implementation later if you need to.
- 如果收集不应该被外界所改变,使用
的IEnumerable&LT; T&GT;
。
- 如果收集的将会的由外界来改变,使用
的ICollection&LT; T&GT;
- 如果索引的访问是必须的,使用
的IList&LT; T&GT;
。
- If the collection should not be changed by the outside world, use
IEnumerable<T>
. - If the collection will be changed by the outside world, use
ICollection<T>
. - If indexed access is required, use
IList<T>
.
在私人实施,它不是那么重要的是使用抽象类:
In a private implementation, it's not as important to use the abstract types:
- 如果您需要索引访问,并知道最终的大小,使用
T []
或名单,其中,T&GT;
。 - 如果您需要索引访问,不知道最后的大小,使用
名单,其中,T&GT;
- 如果您计划访问元素的LIFO模式,使用
堆栈&LT; T&GT;
。
- 如果您计划访问的元素在FIFO模式,使用
问答LT; T&GT;
。
- 如果您需要在开始和列表的末尾访问元素,但不是在中间,使用
的LinkedList&LT; T&GT;
- 如果你不想重复,使用
的HashSet&LT; T&GT;
- If you need indexed access and know the final size, use
T[]
orList<T>
. - If you need indexed access and don't know the final size, use
List<T>
. - If you plan to access elements in a LIFO pattern, use
Stack<T>
. - If you plan to access elements in a FIFO pattern, use
Queue<T>
. - If you need to access elements at the beginning and end of the list, but not in the middle, use
LinkedList<T>
. - If you don't want duplicates, use
HashSet<T>
.
在.NET 4.0中,你有一些更多的选择,但这些都是基础知识。
In .NET 4.0 you have a few more choices, but those are the basics.
这篇关于这是更好地使用数组或列表&LT;&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!