我在尝试使用 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);
}
我只是在设置这个类时做错了吗?