问题描述
我有一个问题,在三个小时的大部分时间内,我一直在head头。我几乎可以肯定我错过了令人眼花obvious乱的东西……
I have a problem which I have been bashing my head against for the better part of three hours. I am almost certain that I've missed something blindingly obvious...
我有一个简单的XML文件:
I have a simple XML file:
<?xml version="1.0" encoding="utf-8"?>
<WeightStore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Records>
<Record actual="150" date="2010-05-01T00:00:00" />
<Record actual="155" date="2010-05-02T00:00:00" />
</Records>
</WeightStore>
我有一个简单的类结构:
I have a simple class structure:
[Serializable]
public class Record
{
[XmlAttribute("actual")] public double weight { get; set; }
[XmlAttribute("date")] public DateTime date { get; set; }
[XmlIgnore] public double trend { get; set; }
}
[Serializable]
[XmlRoot("WeightStore")]
public class SimpleWeightStore
{
[XmlArrayAttribute("Records")]
private List<Record> records = new List<Record>();
public List<Record> Records { get { return records; } }
[OnDeserialized()]
public void OnDeserialized_Method(StreamingContext context)
{
// This code never gets called
Console.WriteLine("OnDeserialized");
}
}
我在调用代码和类文件:
I am using these in both calling code and in the class files:
using System.Xml.Serialization;
using System.Runtime.Serialization;
我有一些呼叫代码:
SimpleWeightStore weight_store_reload = new SimpleWeightStore();
TextReader reader = new StringReader(xml);
XmlSerializer deserializer = new XmlSerializer(weight_store.GetType());
weight_store_reload = (SimpleWeightStore)deserializer.Deserialize(reader);
问题是我希望调用OnDeserialized_Method,但事实并非如此。
The problem is that I am expecting OnDeserialized_Method to get called, and it isn't.
我怀疑这可能与XML反序列化而不是运行时反序列化有关,也许我使用了错误的属性名称,但我无法找出原因
I suspect it might have something to do with the fact that it's XML deserialization rather than Runtime deserialization, and perhaps I am using the wrong attribute name, but I can't find out what it might be.
大家有什么想法吗?
推荐答案
对于XML反序列化,没有等效的 OnDeserialized
。
There's no equivalent of OnDeserialized
for XML deserialization.
有关变通办法,请参见此帖子:
See this post for workarounds: How do you find out when you've been loaded via XML Serialization?
这篇关于为什么不对XML反序列化触发OnDeserialization?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!