我正在使用 Dispose 进行研发。我对 Forms 处理图像资源有疑问。
namespace DisposeTry
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Image mimg = new Bitmap("repository.png"))
image1.Image = mimg;
}
}
}
由于显而易见的原因,我无法使用 mimg.Dispose 或将其包含在“using”中。何时以及如何处置此资源。请指教。
最佳答案
是的,你是对的,你需要手动处置 Bitmap
对象。
The .NET Bitmap class "encapsulates a GDI+ bitmap", that means you should call Dispose on a Bitmap when you are finished with it,
Always call Dispose before you release your last reference to the Image. Otherwise, the resources it is using will not be freed until the garbage collector calls the Image object's Finalize method.
您只需重写 Dispose
方法即可实现此目的。
然而,WinForms 的问题是你的表单是一个分部类,并且有一个部分 YourForm.Designer.cs
,它是由 Visual Studio 自动生成的,并且已经实现了 Dispose
处理WinForms组件的方法。
您需要将此方法移至您的代码中,请参阅this SO question了解更多信息。 .
然后,你的方法将如下所示:
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
mimg.Dispose(); // mimg should be global, of course
}
base.Dispose(disposing);
}
关于c# - 以表单形式处置非托管资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38803241/