52

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>

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?

EDIT: 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.

EDIT: Thanks Marc Gravell and Sean for the answer. Sorry, I can only pick 1 as answer, so I'll up vote both.


I think the comments are required in many situations.

For instance, think of the algorithmic ones. Suppose there is a function written in C which solves the Traveling Salesperson Problem, there are wide range of techniques that can be used to deal with this problem. And the codes are usually cryptic by its nature.

Without explicitly describing the parameters and the algorithm used, by using comments, it is almost impossible to reuse this piece of code.

4

6 に答える 6

84

LINQ 拡張メソッドを で直接使用できますが、 /を挿入しない限り( vsのおかげで) では使用できList<object>ません。タイプセーフなどが必要ない場合でも、これはかなりの価値があります。ArrayListCast<object>()OfType<object>IEnumerable<object>IEnumerable

速度はほぼ同じです。構造体はまだボックス化されているなどです-そのため、それらを区別することは他にあまりありません. ArrayList私は「おっと、誰かがまたレガシーコードを書いている...」と見る傾向があることを除いて;-p

于 2008-12-24T11:08:27.020 に答える
46

を使用する大きな利点の 1 つList<object>は、最近ではほとんどのコードがジェネリック クラス/インターフェイスを使用するように記述されていることです。最近では、ほとんどの人が のIList<object>代わりにを取るメソッドを書くのではないかと思いますIListArrayListは実装されていないため、IList<object>これらのシナリオでは配列リストを使用できません。

私は、非ジェネリックなクラス/インターフェースをレガシー コードと考える傾向があり、可能な限りそれらを避けます。

于 2008-12-24T10:17:01.133 に答える
11

この場合、ArrayListvs.List<Object>その後、速度の違いに気付くことはありません。これらのそれぞれで使用可能な実際のメソッドには、特に .NET 3.5 と拡張メソッドのカウントにいくつかの違いがあるかもしれませんが、それは ArrayList が他の何よりもやや非推奨になっていることに関係しています。

于 2008-12-24T10:17:39.807 に答える
5

Yes, besides being typesafe, generic collections might be actually faster.

From the MSDN (http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx)

The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.

于 2008-12-24T09:38:12.040 に答える
1

ベンチマークを実行すると、何が最も効果的かがわかります。違いは非常に小さいと思います。

于 2008-12-24T12:17:22.187 に答える
-4

List<> is a typesafe version of ArrayList. It will guarantee that you will get the same object type in the collection.

于 2008-12-24T09:34:00.707 に答える