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

但这总是会产生错误。

4

1 回答 1

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.

于 2012-10-26T12:52:53.723 回答