我正在尝试将字节数组转换为对象。为了消除任何可能的问题,我创建了一个简单的窗体,只需调用原始代码中的函数,我就会得到相同的错误。有什么想法发生了什么?
private void button1_Click(object sender, EventArgs e)
{
byte[] myArray = new byte[] {1, 2, 3, 4, 5, 6, 7};
object myObject = ByteArrayToObject(myArray);
if(myObject != null)
{
button1.Text = "good";
}
}
private object ByteArrayToObject(byte[] arrBytes)
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binForm = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream memStream = new MemoryStream(arrBytes);
memStream.Position = 0;
return binForm.Deserialize(memStream);
}
答案 0 :(得分:1)
由于您没有真正说出您对结果对象所做的事情,因此很难给出更具体的答案。但是,一个字节数组已经一个对象:
private void button1_Click(object sender, EventArgs e)
{
byte[] myArray = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
object myObject = myArray as object;
if (myObject != null)
{
button1.Text = "good";
}
}
答案 1 :(得分:1)
BinaryFormatter
不仅仅是读/写字节。
尝试此示例,首先序列化然后读取序列化对象的内容:
byte[] myArray = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binForm = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream memStream = new MemoryStream();
// Serialize the array
binForm.Serialize(memStream, myArray);
// Read serialized object
memStream.Position = 0;
byte[] myArrayAgain = new byte[memStream.Length];
memStream.Read(myArrayAgain, 0, myArrayAgain.Length);
事实证明序列化内容是这样的:
0, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 0, 0, 0, 0, 15, 1, 0, 0, 0, 7, 0, 0, 0, 2, 1, 2, 3, 4, 5, 6, 7, 11
你看,有一个页眉和一个页脚。你的实际对象几乎就在最后。