就个人而言,我不会为此目的使用BinaryFormatter - 它是特定于实现的并且过于昂贵。我很想(其中之一):
1:使用 BinaryWriter / BinaryReader 手动完成(但请注意,这很容易从任何 API 中解释):
// note I've used arrays in the example; lists are identical
int[] data = { 1, 2, 3, 4, 5 };
byte[] raw;
using (var ms = new MemoryStream())
using (var writer = new BinaryWriter(ms))
{
writer.Write(data.Length);
foreach(int i in data) {
writer.Write(i);
}
writer.Close();
raw = ms.ToArray();
}
// read it back
using (var ms = new MemoryStream(raw))
using (var reader = new BinaryReader(ms))
{
int count = reader.ReadInt32();
data = new int[count];
for (int i = 0; i < count; i++)
{
data[i] = reader.ReadInt32();
}
}
或2:使用与实现无关的序列化格式,例如protobuf;这里我使用的是 protobuf-net
int[] data = { 1, 2, 3, 4, 5 };
byte[] raw;
using (var ms = new MemoryStream()) {
Serializer.Serialize(ms, data);
raw = ms.ToArray();
}
// read it back
using (var ms = new MemoryStream(raw)) {
data = Serializer.Deserialize<int[]>(ms);
}
请注意,(1) 示例使用 24 字节(6 * 4 字节); (2) 使用 10 个字节(部分原因是数字很简单,但实际上 protobuf 有一些我们甚至没有在这里使用的技巧(例如“打包”数据))。