1

我在尝试使用 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);
        }

我只是在设置这个类时做错了吗?

4

2 回答 2

1

我最初的印象是从 IXmlSerializable 继承使我能够读取和写入所有传入的 xml 数据。但是,会进行验证以确保类类型相同。因此我需要序列化和反序列化Character

我的意图是能够序列化子类。我通过使用该WriteXml方法并在该方法中使用反射来基于根节点获取关联类型来管理这一点。

我希望这个解释对其他人有所帮助。

于 2012-05-23T16:29:38.297 回答
0
public class UserCharacter : Character
{
    public void ReadXml(XmlReader reader)
    {
        base.ReadXml(reader);
    }
    public void WriteXml(XmlWriter writer)
    {
        base.WriteXml(writer);
    }
}
于 2012-05-23T16:35:20.967 回答