Why and when to inherit from Collection

后端 未结 4 890
我寻月下人不归
我寻月下人不归 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:41

    By stating that you are inheriting the Collection class, you declare that your class IS-A Collection, meaning that you have all it's API implemented (either by the derived class or by base the Collection class).

    The advantage in the inheritance is that you can decide to override some of the methods and handle them in a way you find more suitable to your needs or to the type T (IFoo in your case).

    In the same manner you can also decide to extend your API in order to support some other functionality that you find appropriate for your situation.

    For example if you class IFoo looks some thing like this:

    public interface IFoo
    {
       int a;
       int b;
    }
    

    In your derived class you can add an overload to the Remove that will look something like:

    public bool Remove(int a, int b )...
    

    And it will remove all occurrences of items that has certain values for a and b

提交回复
热议问题