Why and when to inherit from Collection

后端 未结 4 883
我寻月下人不归
我寻月下人不归 2021-01-17 21:08

I\'m tracing legacy code in my project written in C#.

I find the following code:

public class FooCollection : Collection {};
4条回答
  •  时光说笑
    2021-01-17 21:33

    I don't understand why (and when) we need to create our own Collection class like this.

    I never would. I personally find the Collection class to not be useful at all. I have not yet found a use for it.

    One of the main problems with the type is that most of the method aren't virtual. The only virtual methods that are ClearItems, InsertItem, RemoveItem, and SetItem (along with Equals, GetHashCode, and ToString from Object). The rest of the methods/properties aren't virtual, and so cannot be overridden. This means you can alter the semantics for adding/inserting/removing an item slightly, but that's all.

    What's the data structure used in Collection?

    Internally it is backed by a List.

    Why not just use the build-in collection (array, List, Dictionary, ...)

    In virtually all instances you would. While there are occasional instances in which you might actually want to create a brand new collection type, I've never found a use in which Collection was helpful in creating such a custom collection. Generally it's just best to implement some of the interfaces in the Collections namespace, based on what your collection can fulfill, and optionally compose the type using other collections as instance fields, if it is merely an extension of an existing collection.

提交回复
热议问题