Should we use Generic Collection to improve safety and performance?

前端 未结 3 1685
滥情空心
滥情空心 2021-01-24 07:11

Should we use Generic Collection to improve safety and performance?

3条回答
  •  独厮守ぢ
    2021-01-24 07:34

    Absolutely.

    A conventional collection, such as the ArrayList, implicitly stores objects.

    This means, that doing this:

    ArrayList list = new ArrayList();
    list.Add(5);
    list.Add("FooBar");
    

    Is legitimate code. This introduces a handful of issues.

    • Normally, you don't want to store different types in the same collection, and having compile time checking for this is nice.
    • When you store a value type (such as the integer 5 above), it must be boxed into a reference type before it can be stored in the collection.
    • When reading a value, you must cast it back from Object to the desired type.

    However, you eliminate all of these issues by using a generic collection:

    List list = new List();
    list.Add(5);
    // Compile Time Error.
    list.Add("FooBar")
    

    You also gain intellisense support when working directly with indices of the collection, instead of just generic "object" intellisense.

提交回复
热议问题