这是更好地使用数组或列表<>? [英] Which is better to use array or List<>?

查看:163
本文介绍了这是更好地使用数组或列表<>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种类型将有更好的表现,哪些你认为应该使用。

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< T>
  • 如果收集的将会的由外界来改变,使用的ICollection< T>
  • 如果索引的访问是必须的,使用的IList< T>
  • 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[] or List<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屋!

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