【问题标题】:serialize list contain hash table序列化列表包含哈希表
【发布时间】:2012-10-26 10:39:50
【问题描述】:

我有一个类,它有一个字符串和一个哈希表。哈希表包含一组键(字符串)值和每个键属性的位图文件。 如何将其序列化为二进制文件?

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

但这总是会产生错误。

【问题讨论】:

    标签: image serialization bitmap hashtable binary-serialization


    【解决方案1】:

    我可以毫无错误地运行您的代码。调用代码:

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

    您看到的错误是什么?是编译器错误还是运行时异常?我可以在示例诗歌列表上毫无问题地运行此代码。顺便说一句,我建议使用Dictionary&lt;K,V&gt; 而不是HashTable

    【讨论】:

    • 位图 b = 新位图(路径);位图包含图像数据,当我序列化哈希表时,它说位图并不暗示接口可序列化。然后我将图像保存到本地磁盘以实现 percistence。
    • 是的,我怀疑图像可能无法序列化(它包含本机图像资源)。您要做的是序列化原始图像字节。您可以实现自定义序列化逻辑来写入图像的数据(字节),而不是位图对象。
    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 2013-03-16
    • 2015-03-12
    • 2016-11-16
    • 1970-01-01
    • 2023-03-31
    • 2022-01-05
    • 2011-11-16
    相关资源
    最近更新 更多