C# 为什么序列化ImageList不会';工作不好
我使用的是C# 为什么序列化ImageList不会';工作不好,c#,serialization,C#,Serialization,我使用的是二进制格式化程序,我序列化了一个树视图。 现在我想对图像列表做同样的事情 我使用此代码序列化: public static void SerializeImageList(ImageList imglist) { FileStream fs = new FileStream("imagelist.iml", FileMode.Create); BinaryFormatter bf = new BinaryFormatter();
二进制格式化程序
,我序列化了一个树视图。
现在我想对图像列表做同样的事情
我使用此代码序列化:
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
为什么?大多数人没有使用他们的全部资源来交叉引用他们已经知道的内容ImageList
在其当前形式下不可序列化,但只有两件事需要保存在其中,那就是键和图像
。因此,您构建了一个中间类来保存它们,这是可序列化的,如以下示例所示:
[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 { }
}
[Serializable()]
公共类平面图像
{
公共映像_映像{get;set;}
公共字符串_key{get;set;}
}
void Serialize()
{
字符串路径=Options.GetLocalPath(“ImageList.bin”);
BinaryFormatter formatter=新的BinaryFormatter();
List fis=新列表();
对于(int index=0;index<\u smallImageList.Images.Count;index++)
{
FlatImage fi=新的FlatImage();
fi._key=_smallImageList.Images.Keys[index];
fi._image=_smallImageList.Images[index];
财政司司长增加(财政司司长);
}
使用(FileStream-stream=File.OpenWrite(path))
{
序列化(流,fis);
}
}
void反序列化()
{
字符串路径=Options.GetLocalPath(“ImageList.bin”);
BinaryFormatter formatter=新的BinaryFormatter();
尝试
{
使用(FileStream-stream=File.OpenRead(path))
{
List ilc=格式化程序。反序列化(流)为列表;
for(int index=0;index
这是因为ImageListStreamer仅序列化ImageList数据,它不能替代序列化完整的ImageList。您使用它的方式并不打算使用它,它是一个帮助器类,用于将ImageList数据序列化到.resx文件中。设计器使用它。@HansPassant我使用的ImageList可以在运行时更改,我在TreeView中使用它的键来显示图像(在附加它之后),您建议将其保存在哪里?要将其保存在.resx文件中?如果是,怎么做?或者,例如在文本文件中保存键,并在表单加载中填充ImageList键?