简体   繁体   中英

C# XML Serialization excluding parent class fields

I have a class like this:

public abstract class Node : Button
    {
        [XmlIgnoreAttribute()]
        private bool isMovable;

        public abstract ObjectType Type
        {
            get;
        }
        public double X { get; set; }
        public double Y { get; set; }
        public string Nodename { get; set; }
    }

Serialization process:

ObjectXMLSerializer<List<Node>>.Save(main.current_data.Nodes, filename);

The trick happens when I try to serialize it: I don't want its parent's (Button) fields to be serialized, because this gives me serialization errors. So later, I can deserialize this xml to get an array of Nodes created when I read the fields they have. Can I ignore the serialization of the parent's class somehow? Thanks.

I'd go with containment instead. And serialize the contained NodeInfo . Node information would be the specific difference from a wpf button, the additional info you want to serialize.

public class ButtonNode : System.Windows.Controls.Button
{
    private System.Windows.Controls.Button _button;
    public ButtonNode(System.Windows.Controls.Button btn) : base() { this._button = btn; }

    public NodeInfo NodeInfo { get; set; }
}


public interface INodeInfo { ObjectType Type { get; } }

[XmlInclude(typeof(ConcreteNodeInfo1))]
public abstract class NodeInfo : INodeInfo
{
    public NodeInfo() { }

    [XmlIgnore] private bool isMovable;
    public abstract ObjectType Type { get; }
    public double X { get; set; }
    public double Y { get; set; }
    public string NodeName { get; set; }
}

public class ConcreteNodeInfo1 : NodeInfo 
{
    public ConcreteNodeInfo1() : base () { }
    public override ObjectType Type { get { return ObjectType.ObjectType1; }
}

As a side note, this post tackles the 'why shouldn't I use generics with XmlSerializer '.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM