Why and when to inherit from Collection

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

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

    One of the main use cases for implementing a custom Collection is serialization.

    If you want to customize how the collection is serialized (for example to XML, using XmlSerializable), you can create a custom collection class and implement IXmlSerializable on it. Then, you can change how to read or write the collection by manipulating the Read and Write methods of that interface.

    class MyCollection : Collection, IXmlSerializable
    {
        public XmlSchema GetSchema()
        {
            return(null);
        }
    
        public void WriteXml(XmlWriter writer)
        {
            //// foreach (var item in Items)
                //// writer.Write...
        }
    
        public void ReadXml(XmlReader reader)
        {
            //// Items.Add(reader.Read...
        }
    }
    

    This is in most cases preferable compared to implementing IXmlSerializable on the parent class, as it leads to less code overall and promotes reuse (you can reuse the same collection in multiple places and it will be serialized in the same way as long as you use a XmlSerializer to serialize it).

    I've used this recently due to a requirement from an external system that needed each element of the collection to generate a XML node with the index of the element appended to it.

    The final structure looked somewhat like this:

    
      first item
      second item
      ...
    
    

    I'm not fond of coupling the collection to the serialization like this, but sometimes it is a valid approach.

提交回复
热议问题