【问题标题】:Binary Formatter, Set Position to Deserialize Particular Object二进制格式化程序,设置位置以反序列化特定对象 【发布时间】:2013-08-25 07:10:38 【问题描述】:
我想问一下使用二进制格式化程序对对象进行序列化/反序列化。好吧,我正在尝试反序列化 FileStream 中包含许多已被一一序列化的对象的对象。对象的大小太大而无法保存在进程内存中,这就是为什么我不将所有对象打包在一个中,例如: List 因为它们在进程内存中太大所以我尽可能多地序列化根据需要多次。通过这种方式,它不会占用很多进程内存,因为我只是交替处理一个对象而不是所有对象。看看我的意思的草图
序列化对象也成功了,现在我遇到了反序列化对象的问题。
这是问题所在:
在 List 中,我们可以使用索引项。所以如果我们想取第五个索引,我们可以这样称呼它:
List<object> list = new List<object>();
list(0) = "object1";
list(1) = "object2";
list(2) = "object3";
list(3) = "object4";
list(4) = "object5";
list(5) = "object6";
object fifthIndex = list[5]; // here we can get item based index
现在的问题是我怎样才能获得具有第五个索引的对象,就像 List Method 在具有二进制格式化程序的文件流中的六个反序列化对象上。我知道在 FileStream 中有一个名为“FileStream.Position”的属性,但它不喜欢索引,当我反序列化/序列化一个对象时它看起来像一个随机数。也许它会增加随机数。
实际上我已经成功了,但我敢打赌这不是查看我曾经尝试过的代码的最佳方式:
object GetObjectStream(FileStream fs, int index)
{
if (fs != null)
{
BinaryFormatter binaryformatter = new BinaryFormatter();
bool isFinished = false; int count = 0;
while (isFinished == false)
{
try
{
object objectdeserialized = binaryformatter.Deserialize(fs);
if (count == index) return objectdeserialized;
count++;
}
catch
{
isFinished = true;
return null;
}
}
}
return null;
}
----Write objects to file---
1. Keep a Dictionary<KeyType, long> dict. KeyType probably int if you key on an object number.
2. open file FileX for output; FileX.position = 0 at this point.
3. For each object:
update dictionary(oject.key, fileX.Position)
Serialize object to FileX (note: FileX.Position is updated by BinaryFormatter)
4. Close FileX. Save Dictionary (serialize to another file).
----Read Back Object---
Use Dictionary to get offset based on key of object you want:
do FileX.Seek(offset, 0); formatter.deserialize(FileX) to get back the
object you wish.