使用 IXmlSerializable 时未调用 ReadXml
本文关键字:调用 ReadXml IXmlSerializable 使用 | 更新日期: 2023-09-27 18:34:51
我在尝试使用IXmlSerializable时遇到了一些问题。反序列化时似乎不会调用 ReadXml 方法,而 WriteXml 方法会调用。
下面是代码的精简版本。
public interface ICharacter {
string FullName { get; set; }
}
public class Character : ICharacter, IXmlSerializable {
public string FullName { get; set; }
public Character() {
//apply default character information
FullName = string.Empty;
}
}
public void ReadXml(XmlReader reader) {
if (reader == null) return;
//just using null to see if it's called, i've used a break point to check if it was fired
}
public void WriteXml(XmlWriter writer) {
writer.WriteElementString("FullName", FullName);
}
}
要序列化和反序列化,我执行以下操作:
//serialise example
Character character = new Character();
using (StringWriter stringWriter = new StringWriter()) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Character));
xmlSerializer.Serialize(stringWriter, character);
xml = stringWriter.ToString();
}
//deserialise example
using (StringReader stringReader = new StringReader(xml)) {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(UserCharacter));
_character = (Character)xmlSerializer.Deserialize(stringReader);
}
我只是在本课程的设置上做错了什么吗?
我最初的印象是,从IXmlSerializable继承使我能够读取和写入所有传入的xml数据。但是,执行验证以确保类类型相同。因此,我需要序列化和反序列化Character
。
我的目的是能够序列化子类。我通过使用 WriteXml
方法并在该方法中使用反射来获取基于根节点的关联类型来管理此问题。
我希望这个解释对其他人有所帮助。
public class UserCharacter : Character
{
public void ReadXml(XmlReader reader)
{
base.ReadXml(reader);
}
public void WriteXml(XmlWriter writer)
{
base.WriteXml(writer);
}
}