2013-04-02 36 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 

你看,有一個頁眉和一個頁腳。你的實際對象幾乎在最後。

相關問題