我有一个具有不同值的对象/类作为成员,所有可序列化,我可以将一个对象转换为byte []和其他方式。 我正在将这些对象的列表转换为一个大字节数组,如何将其转换回来?
示例对象:
using System;
using System.IO;
[Serializable]
public class MyItem {
internal string m_name = "";
internal int m_position = 0;
internal float m_color = 0f;
internal int m_direction = 0;
internal float m_power = 0f;
public MyItem(string name, int position, float color, int direction, float power) {
m_name = name;
m_position = position;
m_color = color;
m_direction = direction;
m_power = power;
}
public byte[] Serialize() {
using (MemoryStream m = new MemoryStream()) {
using (BinaryWriter writer = new BinaryWriter(m)) {
writer.Write(m_name);
writer.Write(m_position);
writer.Write(m_color);
writer.Write(m_direction);
writer.Write(m_power);
}
return m.ToArray();
}
}
public static MyItem Desserialize(byte[] data) {
string name;
int position;
float color;
int direction;
float power;
using (MemoryStream m = new MemoryStream(data)) {
using (BinaryReader reader = new BinaryReader(m)) {
name = reader.ReadString();
position = reader.ReadInt32();
color = reader.ReadSingle();
direction = reader.ReadInt32();
power = reader.ReadSingle();
}
}
return new MyItem(name, position, color, direction, power);
}
}
转换为字节数组:
List<MyItem> itemlist = <...>;
List<byte[]> byteList = new List<byte[]>();
for (int i = 0; i < itemlist.Count; i++) {
byteList.Add(itemlist[i].Serialize());
}
byte[] data = byteList.SelectMany(bytes => bytes).ToArray();
转换回来:
????????
答案 0 :(得分:1)
如注释中所述,您需要在流中写入每个对象的字节,以便能够反序列化单个对象。例如:
public static class MyItemSerializer
{
public static byte[] Serialize(this IEnumerable<MyItem> items)
{
using (MemoryStream m = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(m, System.Text.Encoding.UTF8, true))
{
foreach (var item in items)
{
var itemBytes = item.Serialize();
writer.Write(itemBytes.Length);
writer.Write(itemBytes);
}
}
return m.ToArray();
}
}
public static List<MyItem> Deserialize(byte[] data)
{
var ret = new List<MyItem>();
using (MemoryStream m = new MemoryStream(data))
{
using (BinaryReader reader = new BinaryReader(m, System.Text.Encoding.UTF8))
{
while (m.Position < m.Length)
{
var itemLength = reader.ReadInt32();
var itemBytes = reader.ReadBytes(itemLength);
var item = MyItem.Desserialize(itemBytes);
ret.Add(item);
}
}
}
return ret;
}
}
您可以在此处看到它:https://dotnetfiddle.net/Nk2cks
但.NET已经包含一个名为BinaryFormatter