C# .NET:派生类中的XmlAttribute

C# .NET:派生类中的XmlAttribute,c#,.net,serialization,xml-serialization,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 bar

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

[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;

}
包含两个XML属性。派生类:

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;
        }
    }
[XmlArray]
[XmlArrayItem(typeof(Column))]
公共列表列
{
得到
{
返回列;
}
设置
{
列=值;
}
}
正在序列化为基类实例的集合-未序列化列类中声明为XmlAttribute的字段。谁能解释一下为什么会发生这种情况?如何使派生类中的XmlAttributes也可序列化


非常感谢,

我已经尝试了上面的代码,一切正常。我创建了一个包含三列的列表,并将其序列化为三个“列”节点,其中包含两个属性。我还尝试了一个列表,添加了一个列和一个梁,得到了一个列和一个节点。这就是你想做的吗?