数组与列表 [英] Array vs List

查看:52
本文介绍了数组与列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#应用​​程序中,我需要将EmpId列表作为参数传递给method()

In my c# application I need to pass a list of EmpIds as a parameter to a method()

Like

DisplayName (string[] ids);


DisplayName (List<string> ids);



您更喜欢哪一个:数组或列表.
回答时,请同时考虑性能.

[edit]标记,代码块已移至左右代码,英语和标点符号已整理. -OriginalGriff [/edit]



Which one would you prefer: array or list.
Please consider performance as well while answering.

[edit]Tags, codeblock moved to around code, English and punctuation tidied. - OriginalGriff[/edit]

推荐答案

有关此主题的说法很多-请参见
A lot has been said on this topic - see here[^].


在性能方面,不会有'在方法调用上没有区别-在任何一种情况下,传递的都是单个引用.

哪个最好?
取决于您在做什么.如果它是固定的字符串数组,并且在编译时知道字符串的数量,并且它们在运行时不更改数量,内容或顺序,那么最好使用数组.

如果该号码未知,则列出.如果项目的顺序或数量发生变化,请列出.

没有最佳"解决方案-它取决于您的代码以及您要实现的目标.请记住,可以随时将List转换为数组...
Performance wise, there won''t be a difference in the method call - all that is passed is a single reference in either case.

Which is best?
Depends on what you are doing. If it is a fixed array of strings, where the number of strings is known at compile time, and they do not change number, content or order at run time, then an array may be best.

If the number is not known, then List. If the order or number of items changes, List.

There is no "best" solution - it will depend on your code, and what you are trying to achieve. Bear in mind that a List can be converted to an array at any time...


如果函数仅需要对集合的只读访问,则可以使用IEnumerable<string>ReadOnlyCollection<string> .这样,它将无法修改集合.对于数组,风险只是修改条目的风险,长度不能更改.使用该列表,该功能除了具有修改条目的风险外,还可以删除/添加条目,从而更改集合的长度.所以也有需要考虑的地方.
If the function needs purely readonly access to the collection, you could use IEnumerable<string> or ReadOnlyCollection<string>. That way it will not be able to modify the collection. With the array, the risk is merely that of modified entries, the length cannot be changed. With the list, in addition to the risk of modified entries, the function can also remove/add entries and thus change the length of the collection. So there''s that to consider too.


这篇关于数组与列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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