我使用 C# .net 4.0,但看不到任何可行的方法,但也许您知道吗? :)
我以这种方式进行序列化:
public static void SaveCollection<T>(string file_name, T list)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = null;
try
{
fs = new FileStream(Application.StartupPath + "/" + file_name, FileMode.Create);
bf.Serialize(fs, list);
fs.Flush();
fs.Close();
}
catch (Exception exc)
{
if (fs != null)
fs.Close();
string msg = "Unable to save collection {0}\nThe error is {1}";
MessageBox.Show(Form1.ActiveForm, string.Format(msg, file_name, exc.Message));
}
}
请您参考如下方法:
因此,假设您实际上事先知道对象图的大小,这本身可能很困难,但我们假设您知道 :)。你可以这样做:
public class MyStream : MemoryStream {
public long bytesWritten = 0;
public override void Write(byte[] buffer, int offset, int count) {
base.Write(buffer, offset, count);
bytesWritten += count;
}
public override void WriteByte(byte value) {
bytesWritten += 1;
base.WriteByte(value);
}
}
然后你可以像这样使用它:
BinaryFormatter bf = new BinaryFormatter();
var s = new MyStream();
bf.Serialize(s, new DateTime[200]);
这将为您提供写入的字节数,因此您可以使用它来计算时间。注意:您可能需要重写流类的更多方法。
