我有一大堆需要在HTML表中显示的对象。我使用BinaryFormatter检索列表,如下所示:
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
MyObject obj = (MyObject) formatter.Deserialize(fromStream);
stream.Close();
Deserialize()方法是否可以返回前100条记录,然后再返回100条记录,依此类推?
答案 0 :(得分:1)
Deserialize()方法可以返回前100条记录,然后返回100条记录 等等?
简短的回答是“否”。
1)但是,您可以逐步浏览反序列化的对象,例如下面的地址:
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
public class App
{
[STAThread]
static void Main()
{
Serialize();
Deserialize();
}
static void Serialize()
{
// Create a hashtable of values that will eventually be serialized.
Hashtable addresses = new Hashtable();
addresses.Add("Jeff", "123 Main Street, Redmond, WA 98052");
addresses.Add("Fred", "987 Pine Road, Phila., PA 19116");
addresses.Add("Mary", "PO Box 112233, Palo Alto, CA 94301");
// To serialize the hashtable and its key/value pairs,
// you must first open a stream for writing.
// In this case, use a file stream.
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
static void Deserialize()
{
// Declare the hashtable reference.
Hashtable addresses = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
// To prove that the table deserialized correctly,
// display the key/value pairs.
foreach (DictionaryEntry de in addresses)
{
Console.WriteLine("{0} lives at {1}.", de.Key, de.Value);
}
}
}
2)首先选择一种不同的编码二进制数据的方法,以便您可以根据需要顺序读取它。因此,例如,您可以编写一个自定义的序列化程序,该序列化程序首先根据要流式传输的对象的大小,将要读取的字节数作为字节序列输出:
int read = stream.Read(data, offset, remaining);
实际上,编写您自己的序列化程序,以便您了解如何对数据进行序列化,并根据需要逐个反序列化数据,如果这是您的要求,那么可能值得付出努力。
3)依靠有效地序列化数据并允许您顺序读取内容的第三方软件包。有堆在那里,只是做一些谷歌搜索会发现堆,但是您可以看一下说Google协议缓冲区,它高效且快速。请参阅https://developers.google.com/protocol-buffers/docs/csharptutorial,其中提供了一些我已经讨论过的内容的示例。