【发布时间】:2014-07-10 15:45:06
【问题描述】:
我有一个如下所示的游戏数据类:
public class SaveGameData {
public virtual List<PropertyContainer> properties {get; set; }
}
还有这些类:
public class PropertyContainer {
public Property property {get; set; }//Could be set to DerivedProperty
}
public class Property {
public int BasePropertyData {get; set;}
}
public class DerivedProperty : Property {
public int DerivedPropertyData {get; set; }
}
我正在尝试在播放会话之间保存/加载这些数据,我正在为此过程使用 XML 序列化/反序列化。
问题在于,在 PropertyContainer 类中,派生的属性有时会被用来替代 Property 类,如下所示:
PropertyContainer container = new PropertyContainer();
container.property = derivedProperty;
当容器被序列化时,派生类及其特殊属性也被保存了,这里没问题。
序列化代码如下:
serializer = new System.Xml.Serialization.XmlSerializer(typeof(SaveGameData));
SaveGameData dataToSave = GetSaveGameData();
using (var stream = new StringWriter()) {
serializer.Serialize(stream, dataToSave);
...write to file...
}
序列化过程似乎正在工作,因为派生类被正确识别并保存到 XML 文件中,XML 输出如下所示:
<?xml version="1.0" encoding="utf-16"?>
<SaveGameData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<properties>
<PropertyContainer>
<property xsi:type="DerivedProperty">
<BasePropertyData>1</BasePropertyData>
<DerivedPropertyData>1</DerivedPropertyData>
</property>
</PropertyContainer>
</properties>
</SaveGameData>
但是当 XML 文件被反序列化时,所有的派生类都会被丢弃。下面是反序列化代码:
SaveGameData result;
string data = ReadSaveGameData();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(SaveGameData));
using (StringReader stream = new StringReader(savedGame)) {
result = (SaveGameData)serializer.Deserialize(stream);
}
这意味着在加载 XML 数据后,在派生属性上调用 GetType()(例如 saveGameData.properties[0].GetType(),假设属性是 DerivedProperty)将生成基类,即 Property;通过扩展,它丢弃了所有 DerivedProperty 的属性。有问题。
附注:
我尝试添加XmlInclude 属性,但没有任何改变:
[System.Xml.Serialization.XmlInclude(typeof(DerivedProperty))]
public class Property {
...
}
我该如何解决这个问题?我的方法是否有可行的替代方案?
【问题讨论】:
标签: c# xml serialization deserialization xml-deserialization