Is List<Object> a good replacement for ArrayList?

筅森魡賤 提交于 2019-12-25 02:22:15

问题


ArrayList, which I use in legacy Compact Framework code, does not seem to be available in newfangled (.NET 4.5.1) code.

I am storing instances of custom classes in it.

What is a good replacement for it - List<Object>, or is there something more suitable?


回答1:


As @HighCore mentioned in his comment, you should use the generic form of List, List<T>. If you have several classes defined that you need to include in that List, they probably have common properties, methods. In that case, you can make an abstract class for the group of classes.

List<Object> is a possible replacement, but not a good one.




回答2:


Yes, List<object> is a good replacement for ArrayList.

If you want to have a list type that can store anything, you can use either ArrayList or List<object> as the collection type. It will have the same performance and behavior characteristics.

The question is this: Why are you using ArrayList to begin with? If you're coming from a pre-generics version of .NET, then you probably have no choice. You either have strongly typed arrays (which are constant in size) or you have ArrayList which is dynamic in size but overly "generic" in type. It can store anything.

Now, with the new .NET and C# versions, it's time to let all that go.

(regarding comments about "net .NET and C# version": obviously "new" here is not new as in 2014-new, but compared to whatever textbook or sourcecode the OP has learned from generics is "new" compared to using ArrayList.)

You want your collections to be strongly typed. It makes your life easier since you know what fields/properties/members are available on the items of the collection etc.

As such, what you want to do is to figure out what the base type of your elements are, and make the collection a List<BaseType> or similar, this will make your life a whole lot easier.

If you're storing a bunch of integers, use List<int>. If you're storing a bunch of strings, use List<string>. If you're storing a bunch of objects of type SomeCustomObject, use List<SomeCustomObject.



来源:https://stackoverflow.com/questions/22570189/is-listobject-a-good-replacement-for-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!