.NET:Derived类中的XmlAttribute

时间:2014-08-19 11:27:08

标签: c# .net serialization xml-serialization

我正在尝试序列化包含从同一基类派生的类实例集合的大类。基类:

[XmlInclude(typeof(Column))]
[XmlInclude(typeof(Beam))]
[XmlInclude(typeof(FloorTruss))]
[XmlInclude(typeof(PanelBar))]
public abstract class BarBase
{
    #region Constructors

    public BarBase(int id, BarType barType)
    {
        this.Id = id;
        this.BarType = barType;
    }

    #endregion

    #region Public Properties

    [XmlAttribute]
    public BarType BarType
    {
        get
        {
            return barType;
        }
        set
        {
            barType = value;
        }
    }

    [XmlAttribute]
    public int Id
    {
        get
        {
            return id;
        }
        set
        {
            id = value;
        }
    }

    #endregion

    private int id;

    private BarType barType;

}

包含两个XmlAttributes。派生类:

public class Column : BarBase
{
    public Column()
        : base(0, BarType.BT_Invalid)
    {
        this.position = "";
        this.shortName = "";
    }


    public Column(int id, BarType barType, string position, string shortName)
        : base(id, barType)
    {
        this.position = position;
        this.shortName = shortName;
    }

    [XmlAttribute]
    public string Position
    {
        get
        {
            return position;
        }
    }
    [XmlAttribute]
    public string ShortName
    {
        get
        {
            return shortName;
        }
    }

    private readonly string position;
    private readonly string shortName;
}

再添两个。我有一个很大的类,它存储了很少的派生类集合。当我想使用

序列化它们时
    public static string Serialize(Structure structure, string xmlFilePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Structure));
        StringBuilder builder = new StringBuilder();
        StringWriter writer = new StringWriter(builder);
        serializer.Serialize(writer, structure);
        var result = builder.ToString();
        StreamWriter file = new StreamWriter(xmlFilePath);
        file.WriteLine(result);
        file.Close();
        return result;
    }

声明为:

的集合
    [XmlArray]
    [XmlArrayItem(typeof(Column))]
    public List<Column> Columns
    {
        get
        {
            return columns;
        }
        set
        {
            columns = value;
        }
    }

被序列化为基类实例的集合 - 在Column类中声明为XmlAttribute的字段未被序列化。谁能解释一下为什么会发生这种情况?如何使派生类中的XmlAttributes也可序列化?

非常感谢,

0 个答案:

没有答案
相关问题