2013-04-02 22 views
1

我试图将字节数组转换为对象。为了消除任何可能的问题,我创建了一个简单的窗体,它简单地调用了原始代码中打破的函数,并得到相同的错误。关于发生什么事情的任何想法?序列化异常:分析完成之前遇到的流结束 - C#

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); 
    } 
+3

什么让你觉得那个特定的字节数组产生一个有效的对象? –

+0

什么会限定或取消一个字节数组生成一个有效的对象的资格? –

+1

二进制序列化不仅仅是序列化字节。它是*类型安全的*,它将元数据添加到描述对象的流中。 –

回答

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"; 
    } 
} 
+0

我刚刚有一个库函数需要其参数之一是一个对象,我需要传递一堆数据。我已经找到了将字节数组转换为网页上的对象并在一堆地方使用的代码,所以我认为这是它的完成方式。 –

+0

@KhaledBoulos如果你有一个参数是一个对象,你不需要转换任何东西......一切都是一个对象。当然不会序列化它......只需调用'method(myArray)' –

+0

@caerolus - true。我用'as'来证明它可以编译,然后可能在运行时失败。实际上原来的行是'object myObject = myArray;' –

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 

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

相关问题