且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我尝试删除图片框中使用的图像时出现错误

更新时间:2022-06-22 23:56:56

您的标题具有误导性.引发的行不是 Delete ,而是 Dispose .

Your title is misleading. The line that throws is not the Delete but the Dispose.

您已经将其设置为 null ,因此不能再对其进行 Dispose 了.改用它:

You have already set it to null, so you can't Dispose of it any more. Use this instead:

   ..
   if (PatientImage.Image != null)
   {
      Image dummy = PatientImage.Image; 
      PatientImage.Image = null; 
      dummy.Dispose(); 
   }
   ..

首先,我们为图像存储一个新的虚拟引用;然后从控件中清除引用,最后使用虚拟引用释放GDI资源.

First we store a new dummy reference to the image; then we clear the reference from the control and finally we use the dummy reference to free the GDI resources.

每当您要为 PictureBox 设置新的 Image 时,也建议这样做.

This is also recommended whenever you want to set a new Image to a PictureBox.

(这看起来比处理 reference 变量时要复杂的多;但这不是 PictureBox.Image 是什么.这是一个属性,幕后还有各种各样的附加功能.)

(This looks a little more complicated than one would expect when dealing with reference variables; but that is not what PictureBox.Image is. It is a property with all sorts of extras going on behind the scenes..)