简体   繁体   English

C#是有理由使用ArrayList而不是List <T> 了吗?

[英]C# is there ever a reason to use ArrayList instead of List<T> anymore?

The title pretty much sums it up. 标题几乎总结了它。 Now that we have List<T> 's why would anyone want to use an ArrayList instead? 现在我们有了List<T> ,为什么有人想要使用ArrayList呢? The only reason I can think of is if you are forced to use an old version of .NET before List<T> was implemented? 我能想到的唯一原因是,如果在实现List<T>之前你被迫使用旧版本的.NET?

As you said, if for some reason you are stuck with .Net 1.1 then you don't have a choice. 如你所说,如果由于某种原因你被.Net 1.1困住,那么你没有选择。

Your question seems to indicate that there is a choice. 你的问题似乎表明有一个选择。 So then there is no reason to user ArrayList . 那么就没有理由使用ArrayList Anything that ArrayList can do, List<T> can do as well, if not better. ArrayList可以做的任何事情, List<T>也可以做,如果不是更好的话。

Short answer, no. 简短的回答,没有。 ArrayList was from when .NET didn't support generics. ArrayList来自.NET不支持泛型的时候。 List is the more flexible (generic) way to handle lists. List是处理列表的更灵活(通用)方式。 In fact, I don't think Silverlight even supports ArrayLists at all. 事实上,我认为Silverlight根本不支持ArrayLists。

ArrayList is mostly for backward compatibility. ArrayList主要用于向后兼容。 In a project when there is a deadline, you may have the time to convert everything from ArrayList to generic List. 在有截止日期的项目中,您可能有时间将所有内容从ArrayList转换为通用List。

Another reason is that you may be using a library that is written in .NET 1.1. 另一个原因是您可能正在使用.NET 1.1编写的库。 So you may force to use ArrayList in your code, and most likely convert it to a generic List for easy coding. 因此,您可以强制在代码中使用ArrayList,并且很可能将其转换为通用List以便于编码。

However, there are some differences and you may want to read this: .NET: ArrayList vs List 但是,存在一些差异,您可能需要阅读: .NET:ArrayList vs List

You said it yourself: backwards compatibility. 你自己说:向后兼容。 There's no use for it any more, but it clearly can't be removed from the BCL as it'd break existing code that for whatever reason must be compiled against .NET 1.1. 它已经没有用了,但它显然无法从BCL中删除,因为它会破坏现有代码,无论出于何种原因必须针对.NET 1.1进行编译。

唯一一次使用过ArrayList,因为.Net 2.0与vb.net中内置的My.Settings功能一起使用,而且我已经知道我可能会在那里找到一个通用列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM