1

我正在尝试将字节数组转换为对象。为了消除任何可能的问题,我创建了一个简单的 windows 窗体,它只是调用破坏我的原始代码的函数,我得到了同样的错误。关于发生了什么的任何想法?

    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);
    }
4

2 回答 2

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";
    }
}
于 2013-04-02T02:30:58.960 回答
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

你看,有一个页眉和一个页脚。你的实际对象几乎在最后。

于 2013-04-02T02:34:56.083 回答