.NET XML Serialization and inheritance

前端 未结 6 494
别跟我提以往
别跟我提以往 2021-02-04 12:08

I have structure like this:

public interface A
{
    public void method();
}

public class B : A
{
}

public class C : A
{
}

List list;
6条回答
  •  醉话见心
    2021-02-04 12:33

    Yes, but you have to play with the XmlElement, XmlRoot and XmlArray Attributes. Each Type needs it's own element name.

    EDIT: Some sample code. All classes are derived from a common base class.

    Here is a sample code:

    [XmlRoot(ElementName="Root")]
    public sealed class SomeObject
    {
    
        private BaseObject _Object;
    
        [XmlElement(Type=typeof(App.Projekte.Projekt), ElementName="Projekt")]
        [XmlElement(Type=typeof(App.Projekte.Task), ElementName="Task")]
        [XmlElement(Type=typeof(App.Projekte.Mitarbeiter), ElementName="Mitarbeiter")]
        public BaseObject Object
        {
            get
            {
                return _Object;
            }
            set
            {
                _Object = value;
            }
        }
    }
    

    EDIT: Remove Serialization Attribute as it's not needed (but is needed in my project where the code is from)

提交回复
热议问题