2012-10-26 77 views
0

我有一個類有一個字符串和一個哈希表。哈希表包含每個關鍵屬性的鍵(字符串)值和位圖文件集。 我該如何將此序列化爲二進制文件?序列化列表包含散列表

public void SerializeObject(List<Poem> poems) 
    { 

     using (Stream stream = File.Open("data.bin", FileMode.Create)) 
     { 
      BinaryFormatter bin = new BinaryFormatter(); 
      bin.Serialize(stream, poems); 
     } 
    } 

    public List<Poem> DeSerializeObject() 
    { 
     List<Poem> poems1; 
     using (Stream stream = File.Open("data.bin", FileMode.Open)) 
     { 
      BinaryFormatter bin = new BinaryFormatter(); 

      var lizards2 = (List<Poem>)bin.Deserialize(stream); 
      poems1 = (List<Poem>)lizards2; 
     } 
     return poems1; 
    } 

//詩類

[Serializable()] 
public class Poem 
{ 
    string poemName; 
    Hashtable poemContent; contains set of keys(strings) , values(bitmap)// 

    public Poem() { 

     poemContent = new Hashtable(); 

    } 
    public string PoemName 
    { 
     get { return poemName; } 
     set { poemName = value; } 
    } 

    public Hashtable PoemContent 
    { 
     get { return poemContent; } 
     set { poemContent = value; } 
    }} 

但總是產生錯誤。

回答

1

我可以無誤地運行你的代碼。主叫代碼:

SerializeObject(new List<Poem> 
           { 
            new Poem 
             { 
              PoemContent = new Hashtable {{"Tag", new System.Drawing.Bitmap(1, 1)}}, 
              PoemName = "Name" 
             } 
           }); 

var poems2 = DeserializeObject(); 

您看到的錯誤是什麼?它是編譯器錯誤還是運行時異常?我可以在沒有問題的情況下在示例列表中運行此代碼。順便說一下,我建議使用Dictionary<K,V>而不是HashTable

+0

位圖b =新的位圖(路徑);位圖包含一個圖像數據,當我序列化哈希表它說,位圖並不意味着一個接口iserializable。然後我將圖像保存到本地磁盤以達到percistence。 – Hashan

+0

是的,我懷疑圖像可能不是可序列化的(它包含本地圖像資源)。你想要做的是序列化原始圖像字節。您可以實現自定義序列化邏輯來寫入圖像的數據(字節),而不是位圖對象。 –