数组的反序列化总是给出一个空数组
我有一个自定义抽象基类,其中包含子类,我已使用 ISerialized 将其序列化/反序列化。当我对该类的子类的单个实例进行序列化/反序列化时,一切正常。然而,当我做一个数组时,我总是在反序列化时得到一个空数组。序列化是通过 BinaryFormatter 完成的。
这些项目包含在 a 中:
public ObservableCollection<Trade> Trades { get; private set; }
序列化时,这是在 SerializationInfo 参数上的 GetObjectData 中完成的:
Trade[] trades = (Trade[])Trades.ToArray<Trade>();
info.AddValue("trades", trades);
反序列化时,这是在序列化构造函数中以及 SerializationInfo 参数上完成的:
Trade[] trades = (Trade[])info.GetValue("trades", typeof(Trade[]));
foreach (Trade t in trades)
{
Trades.Add(t);
}
反序列化总是给我一个 null 数组,正如我之前提到的,使用以下代码可以很好地对单个项目进行序列化和反序列化:
序列化(GetObjectData 方法):
info.AddValue("trade", Trades.First<Trade>());
反序列化(序列化构造函数):
Trade t = (Trade)info.GetValue("trade", typeof(Trade));
Trades.Add(t);
这是一个常见问题吗?我似乎至少没有发现其他人遇到过这种情况。希望有一个解决方案:),如果我需要向您提供更多信息/代码,请告诉我。
谢谢!
I have a custom abstract base class with sub classes that I've made serializable/deseriablizeable with ISerializable. When I do serialization/deserialization of single instances of this class' sub classes, everything works fine. However, when I do an array of them I always end up with an array of nulls on deserialization. Serialization is done with BinaryFormatter.
The items are contained within a:
public ObservableCollection<Trade> Trades { get; private set; }
On serialization this is done in GetObjectData on the SerializationInfo parameter:
Trade[] trades = (Trade[])Trades.ToArray<Trade>();
info.AddValue("trades", trades);
And on deserialization this is done in the serialization constructor also on the SerializationInfo parameter:
Trade[] trades = (Trade[])info.GetValue("trades", typeof(Trade[]));
foreach (Trade t in trades)
{
Trades.Add(t);
}
Deserialization always gives me an array of nulls and as I mentioned earlier, a single item serializes and deseriaizes just fine with this code:
Serialization (GetObjectData method):
info.AddValue("trade", Trades.First<Trade>());
Deserialization (Serialization Constructor):
Trade t = (Trade)info.GetValue("trade", typeof(Trade));
Trades.Add(t);
Is this a common problem? I seem to find no occurrences of anyone else running in to it at least. Hopefully there is a solution :) and if I need to supply you with more information/code just tell me.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数组首先反序列化。然后所有内部反序列化就完成了。因此,当您尝试访问项目时,它们为空。
并希望在某些方法上使用
[OnDeserialized]
属性,以构建所有其他属性。这是一个例子:Array deserializes first. Then all inner deserialization is done. So when you try to access items, they are null.
And idea to use
[OnDeserialized]
Attribute on some method, that builds up all other properies. And here is example: