【问题标题】:Why serializing an ImageList doesn't work well为什么序列化 ImageList 不能正常工作
【发布时间】:2014-04-15 13:01:54
【问题描述】:

我使用的是BinaryFormatter,我序列化了一个树视图。 现在我想为ImageList做同样的事情

我用这段代码序列化了:

    public static void SerializeImageList(ImageList imglist)
    {
        FileStream fs = new FileStream("imagelist.iml", FileMode.Create);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, imglist.ImageStream);
        fs.Close();

    }

还有这个要反序列化:

    public static void DeSerializeImageList(ref ImageList imgList)
    {
        FileStream fs = new FileStream("imagelist.iml", FileMode.Open);
        BinaryFormatter bf = new BinaryFormatter();
        imgList.ImageStream = (ImageListStreamer)bf.Deserialize(fs);
        fs.Close();

    }

但我在所有键中都得到一个空字符串!

ImgList.Images.Keys

为什么?

【问题讨论】:

  • 因为ImageListStreamer只序列化ImageList数据,不能替代序列化一个完整的ImageList。您正在以不打算使用的方式使用它,它是一个帮助类,用于将 ImageList 数据序列化为 .resx 文件。设计师使用它。
  • @HansPassant 我使用的 ImageList 可以在运行时更改,我在 TreeView 中使用它的键来显示图像(附加后),您建议将其保存在哪里?将其保存在 .resx 文件中?如果是这样,如何?或者例如将键保存在文本文件中并在表单加载中填充 ImageList 键?

标签: c# serialization


【解决方案1】:

大多数人不会使用他们的全部资源来交叉引用他们已经知道的内容。 ImageList 在其当前形式下是不可序列化的,但您真正想要在其中保存的只有两件事,那就是 KeyImage。所以你构建了一个中间类来保存它们,它是可序列化的,如下例所示:

[Serializable()]
public class FlatImage
{
    public Image _image { get; set; }
    public string _key { get; set; }
}

void Serialize()
{
    string path = Options.GetLocalPath("ImageList.bin");
    BinaryFormatter formatter = new BinaryFormatter();

    List<FlatImage> fis = new List<FlatImage>();
    for (int index = 0; index < _smallImageList.Images.Count; index++)
    {
        FlatImage fi = new FlatImage();
        fi._key = _smallImageList.Images.Keys[index];
        fi._image = _smallImageList.Images[index];
        fis.Add(fi);
    }

    using (FileStream stream = File.OpenWrite(path))
    {
        formatter.Serialize(stream, fis);
    }
}

void Deserialize()
{
    string path = Options.GetLocalPath("ImageList.bin");
    BinaryFormatter formatter = new BinaryFormatter();
    try
    {
        using (FileStream stream = File.OpenRead(path))
        {
            List<FlatImage> ilc = formatter.Deserialize(stream) as List<FlatImage>;

            for( int index = 0; index < ilc.Count; index++ )
            {
                Image i = ilc[index]._image;
                string key = ilc[index]._key;
                _smallImageList.Images.Add(key as string, i);
            }
        }
    }
    catch { }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 2016-07-16
    相关资源
    最近更新 更多