编程语言
首页 > 编程语言> > c# – 处理ImageList

c# – 处理ImageList

作者:互联网

处理ImageList对象的适当方法是什么?

假设我有一个私有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,idisposable,winforms,imagelist
来源: https://codeday.me/bug/20190621/1250882.html