How to implement Xml Serialization with inherited classes in C#

后端 未结 2 1400
无人及你
无人及你 2020-12-18 21:21

I have two classes : base class name Component and inheritd class named DBComponent

[Serializable]
public class Component
{
    private string name = strin         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-18 22:11

    Two options for different scenrios: tell the base-class

    [XmlInclude(typeof(DBComponent))]
    public class Component
    {
        private string name = string.Empty;
        private string description = string.Empty;  
    }
    

    Or: tell the collection:

    [XmlArray]
    [XmlArrayItem("Component", typeof(Component))]
    [XmlArrayItem("DBComponent", typeof(DBComponent))]
    public List Components {...}
    

    Actually, you can also use [XmlElement(...)] in place of [XmlArrayItem] if you don't want the outer node (Components). Also: you don't need [Serializable].

提交回复
热议问题