C# 二进制格式化程序在int[,]上失败
在我的程序中,我正在序列化一个二维整数数组。它似乎可以正确序列化,但在反序列化时会引发异常,并显示以下消息: 二进制流“0”不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改 我正在使用BinaryFormatter类型进行序列化/反序列化。我依次注释掉了类上的各个字段,导致失败的是int[,]的一个实例。是什么导致此类型导致反序列化失败?还有其他更合适的类型吗 编辑:以下是代码相关部分的示例: 反序列化:C# 二进制格式化程序在int[,]上失败,c#,.net,serialization,C#,.net,Serialization,在我的程序中,我正在序列化一个二维整数数组。它似乎可以正确序列化,但在反序列化时会引发异常,并显示以下消息: 二进制流“0”不包含有效的BinaryHeader。可能的原因是序列化和反序列化之间的无效流或对象版本更改 我正在使用BinaryFormatter类型进行序列化/反序列化。我依次注释掉了类上的各个字段,导致失败的是int[,]的一个实例。是什么导致此类型导致反序列化失败?还有其他更合适的类型吗 编辑:以下是代码相关部分的示例: 反序列化: int bytesRead = Ssl.End
int bytesRead = Ssl.EndRead(asyncResult);
int bytesToRead = BitConverter.ToInt32(dataBuffer, 0);
dataBuffer = new byte[bytesToRead];
Ssl.Read(dataBuffer, 0, bytesToRead);
MemoryStream ms = new MemoryStream(dataBuffer);
//Add the message to the queue and signal that it is avaible
Message m = (Message)serializer.Deserialize(ms);
系列化:
MemoryStream ms = new MemoryStream();
serializer.Serialize(ms, message);
byte[] data = ms.GetBuffer();
int length = (int)data.Length;
byte[] count = BitConverter.GetBytes(length);
Ssl.Write(count);
Ssl.Write(data);
以及正在序列化的类。数据字段是平铺的一个实例:
[Serializable]
public struct Message
{
public MessageType Type;
public Object Data;
}
[Serializable]
public class Tile
{
[NonSerialized]
public const int Width = 128;
[NonSerialized]
public const int Height = 128;
public Vector3 Location;
public int[,] Heightmap;
public static Tile CreateEmpty(Vector3 location)
{
Tile t = new Tile();
t.Location = location;
t.Heightmap = new int[Width,Height];
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
t.Heightmap[x, y] = 0;
}
}
return t;
}
}
请提供一个简短但完整的程序来演示问题。这将使我们能够更轻松地帮助您。抱歉,我已经编辑了最初的帖子,以包含相关的代码部分。如果您只是将序列化程序的输出直接输入到反序列化程序中,是否也会遇到同样的问题?不会,因此错误一定是在我处理网络时发生的。当其他较小的消息成功时,我发现这很有趣。我会再次检查网络代码,然后报告。谢谢你迄今为止的帮助!这几乎肯定就是问题所在:Ssl.ReaddataBuffer,0,bytesToRead;-你似乎认为你可以在一次通话中阅读全部内容。