处置图像资源 [英] Disposing image resource

查看:84
本文介绍了处置图像资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我正在使用Dispose进行R& D。对于处理图像资源的表格我有疑问。



Hi All,

I am doing an R&D with Dispose. I have a doubt in case of Forms on disposing the image resource.

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





请说明正确的方法。



我尝试了什么:





Please clarify what is the right way.

What I have tried:

namespace DisposeTry
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            using (Image mimg = new Bitmap("repository.png"))
                image1.Image = mimg;   // Obvious error
        }
    }
}

推荐答案

你在使用它时不能处理任何东西 - 这只是愚蠢的 - 而且PictureBox或类似控件中的Image正在使用中可能会看到PictureBox。

如果您创建一个Image,并且Form的生命周期需要它(或者为什么在Load事件中创建它),那么您可以将其置于FormClosed事件,或者当它被另一个图像替换以供显示时。

如果表单是你的主表单,那么你不需要在FormClosed事件处理程序中做任何事情,它将被处理当表单关闭时终止应用程序。
You can't Dispose of anything while it's in use - that's just silly - and an Image in a PictureBox or similar control is in use as long as the PictureBox could potentially be seen.
If you create an Image, and it is needed for the lifetime of the Form (or else why create it in the Load event) then you can Dispose it in the FormClosed event, or when it it replaced by another image for display.
If the Form is your main form, then you don't need to do anything in the FormClosed event handler, it will be disposed for you when the form closes as that terminates the application.


这篇关于处置图像资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆