2012-10-26 139 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

是的,我怀疑图像可能不是可序列化的(它包含本地图像资源)。你想要做的是序列化原始图像字节。您可以实现自定义序列化逻辑来写入图像的数据(字节),而不是位图对象。 –