ArrayList 与 List<object> [英] ArrayList vs List<object>
问题描述
我在 初始化具有未知类型的通用对象上看到了 Jon 的回复:
I saw this reply from Jon on Initialize generic object with unknown type:
如果你想要一个集合包含多种不相关的类型值,但是,您将不得不使用列表<对象>
If you want a single collection to contain multiple unrelated types of values, however, you will have to use
List<object>
我不是在比较 ArrayList
与 List<>
,而是比较 ArrayList
与 List
,因为两者都会暴露 object
类型的元素.在这种情况下使用任何一种都有什么好处?
I'm not comparing ArrayList
vs List<>
, but ArrayList
vs List<object>
, as both will be exposing elements of type object
. What would be the benefit of using either one in this case?
这里不关心类型安全,因为两个类都将 object
作为其项目公开.仍然需要从 object
转换为所需的类型.我对类型安全以外的任何事情都更感兴趣.
It's no concern for type safety here, since both class is exposing object
as its item. One still needs to cast from object
to the desired type. I'm more interested in anything other than type safety.
感谢 Marc Gravell 和 Sean 的回答.抱歉,我只能选择 1 作为答案,所以我会同时投票.
Thanks Marc Gravell and Sean for the answer. Sorry, I can only pick 1 as answer, so I'll up vote both.
推荐答案
您将能够将 LINQ 扩展方法直接用于 List
,但不能用于 ArrayList
,除非你注入了 Cast
/OfType
(感谢 IEnumerable
vs IEnumerable
).即使您不需要类型安全等,这也是值得的.
You'll be able to use the LINQ extension methods directly with List<object>
, but not with ArrayList
, unless you inject a Cast<object>()
/ OfType<object>
(thanks to IEnumerable<object>
vs IEnumerable
). That's worth quite a bit, even if you don't need type safety etc.
速度会差不多;结构体仍然会被装箱,等等 - 所以没有什么可以区分它们的了.除了我倾向于将 ArrayList
视为哎呀,有人又在编写遗留代码了...";-p
The speed will be about the same; structs will still be boxed, etc - so there isn't much else to tell them apart. Except that I tend to see ArrayList
as "oops, somebody is writing legacy code again..." ;-p
这篇关于ArrayList 与 List<object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!