我有一个继承自 List<T>
的类并且还有一些属性,像这样:
[Serializable]
public class DropList : List<DropItem>
{
[XmlAttribute]
public int FinalDropCount{get; set;}
}
这个类被序列化为 xml 作为更大类的一部分:
[Serializable]
public class Location
{
public DropList DropList{get; set;}
....
}
问题是,序列化程序将我的列表视为一个集合;生成的 XML 仅包含列表元素,但不包含类属性(在本例中为 FinalDropCount)。这是输出的 XML 示例:
<Location xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DropList>
<DropItem ProtoId="3" Count="0" Minimum="0" Maximum="0" />
<DropItem ProtoId="4" Count="0" Minimum="0" Maximum="0" />
</DropList>
....
</Location>
有没有什么方法可以保存列表内容和属性而不用执行 IXmlSerializable
用手?
最佳答案
您还有其他可以考虑的选择。
备选方案 - 转向组合而不是继承:
public class DropInfo
{
[XmlArray("Drops")]
[XmlArrayItem("DropItem")]
public List<DropItem> Items { get; set; }
[XmlAttribute]
public int FinalDropCount { get; set; }
}
public class Location
{
public DropInfo DropInfo { get; set; }
}
备选方案二 - 将属性移出集合:
public class DropList : List<DropItem>
{
}
public class Location
{
public DropList DropList { get; set; }
[XmlAttribute]
public int FinalDropCount { get; set; }
}
关于c# - 如何使用 C# XML 序列化序列化 xml 数组和类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2325745/