释放ImageList对象的适当方法是什么?
假设我有一个带有private ImageList imageList成员的类。现在,在某个时候,我执行以下代码:
// Basically, lazy initialization.
if (imageList == null)
{
imageList = new ImageList();
Image[] images = Provider.CreateImages(...);
foreach (var image in images)
{
// Does the 'ImageList' perform implicit copying here
// or does it aggregate a reference?
imageList.Images.Add(image);
// Do I need to do this?
//image.Dispose();
}
}
return imageList;在同一个类中,我有Dispose方法实现,其执行方式如下:
public void Dispose()
{
if (!disposed)
{
// Is this enough?
if (imageList != null)
imageList.Dispose();
disposed = true;
}
}我肯定这段代码有一些潜在的问题,所以你能帮我把它修正一下吗.
发布于 2012-03-06 23:52:31
是的,它是复制的。注意下面的CreateBitMap调用。因此,为了保持尽可能低的资源利用率,您应该取消对dispose行的注释。
private int Add(ImageList.Original original, ImageList.ImageCollection.ImageInfo imageInfo)
{
if (original == null || original.image == null)
throw new ArgumentNullException("value");
int num = -1;
if (original.image is Bitmap)
{
if (this.owner.originals != null)
num = this.owner.originals.Add((object) original);
if (this.owner.HandleCreated)
{
bool ownsBitmap = false;
Bitmap bitmap = this.owner.CreateBitmap(original, out ownsBitmap);
num = this.owner.AddToHandle(original, bitmap);
if (ownsBitmap)
bitmap.Dispose();
}
}
else
{
if (!(original.image is Icon))
throw new ArgumentException(System.Windows.Forms.SR.GetString("ImageListBitmap"));
if (this.owner.originals != null)
num = this.owner.originals.Add((object) original);
if (this.owner.HandleCreated)
num = this.owner.AddIconToHandle(original, (Icon) original.image);
}
if ((original.options & ImageList.OriginalOptions.ImageStrip) != ImageList.OriginalOptions.Default)
{
for (int index = 0; index < original.nImages; ++index)
this.imageInfoCollection.Add((object) new ImageList.ImageCollection.ImageInfo());
}
else
{
if (imageInfo == null)
imageInfo = new ImageList.ImageCollection.ImageInfo();
this.imageInfoCollection.Add((object) imageInfo);
}
if (!this.owner.inAddRange)
this.owner.OnChangeHandle(new EventArgs());
return num;
}当ImageList处理时,它会处理所有图像的副本。因此,是的,在表单以您的身份关闭时,除取消注释其他dispose行外,对其进行处理也是正确的。
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.originals != null)
{
foreach (ImageList.Original original in (IEnumerable) this.originals)
{
if ((original.options & ImageList.OriginalOptions.OwnsImage) != ImageList.OriginalOptions.Default)
((IDisposable) original.image).Dispose();
}
}
this.DestroyHandle();
}
base.Dispose(disposing);
}发布于 2012-03-01 12:08:30
ImageList不拥有对原始图像的引用。当您添加图像时,ImageList会复制它。如果你觉得方便的话,你可以自由地处理原稿。
但是,您应该在Dispose()中调用imageList.Images.Clear();。
https://stackoverflow.com/questions/9515759
复制相似问题