gpt4 book ai didi

c# - 处理 ImageList

转载 作者:太空狗 更新时间:2023-10-30 01:08:24 25 4
gpt4 key购买 nike

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

我确定此代码存在一些潜在问题,请您帮我改正一下。

最佳答案

是的,它制作了一个副本。请注意下面的 CreateBitMap 调用。因此,为了尽可能降低资源使用量,您应该取消注释处理行。

 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 释放时,它释放所有图像的副本。所以,再一次,是的,除了取消注释其他处理行之外,当表单关闭时处理它是正确的。

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

关于c# - 处理 ImageList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9515759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com