解决方法
using System.Xml.Serialization; namespace Custom.Xml.Serialization { public interface IXmlDeserializationCallback { void OnXmlDeserialization(object sender); } public class CustomXmlSerializer : XmlSerializer { protected override object Deserialize(XmlSerializationReader reader) { var result = base.Deserialize(reader); var deserializedCallback = result as IXmlDeserializationCallback; if (deserializedCallback != null) { deserializedCallback.OnXmlDeserialization(this); } return result; } } }
从IXmlDeserializationCallback继承你的类,并在OnXmlDeserialization方法中实现你的同步逻辑.
学分到How do you find out when you’ve been loaded via XML Serialization?
更新:
那么就我所了解的topicstarter来说,他并不想在每次XML反序列化之后“手动”调用一些逻辑.所以,而不是这样做:
public class MyEntity { public string SomeData { get; set; } public void FixReferences() { // call after deserialization // ... } } foreach (var xmlData in xmlArray) { var xmlSer = new XmlSerializer(typeof(MyEntity)); using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData))) { var entity = (MyEntity)xmlSer.Deserialize(memStream); entity.FixReferences(); // do something else with the entity // ... } }
他想做的只是反序列化,而不用担心额外的电话.在这种情况下,提出的解决方案是最干净/最简单的 – 您只需要从IXmlDeserializationCallback接口继承您的实体类,并将XmlSerializer替换为CustomXmlSerializer:
public class MyEntity: IXmlDeserializationCallback { public string SomeData { get; set; } private void FixReferences() { // call after deserialization // ... } public void OnXmlDeserialization(object sender) { FixReferences(); } } foreach (var xmlData in xmlArray) { var xmlSer = new CustomXmlSerializer(typeof(MyEntity)); using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlData))) { var entity = (MyEntity)xmlSer.Deserialize(memStream); // entity.FixReferences(); - will be called automatically // do something else with the entity // ... } }