如果是必要的处置? [英] When is Dispose necessary?

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

问题描述

当你有code这样的:

When you have code like:

Bitmap bmp = new Bitmap ( 100, 100 );
Graphics g = Graphics.FromImage ( bmp );

Pen p = new Pen ( Color.FromArgb ( 128, Color.Blue ), 1 );
Brush b = new SolidBrush ( Color.FromArgb ( 128, Color.Blue ) );

g.FillEllipse ( b, 0, 0, 99, 99 );    
g.FillRegion ( b, pictureBox1.Region );

pictureBox1.BackColor = Color.Transparent;
pictureBox1.Image = bmp;

你有处置的画笔和画刷?那么BMP和对G?

Do you have to dispose the pen and brush? What about bmp and the g?

我的主要问题是,如果这些都必须手工配置,他们为什么不得到当他们走出范围处置?这是会发生什么,如果你没有手动处理它们?它是使人们做到这一点的延迟手动?

My main question is, if these were to be disposed manually, why don't they get disposed as soon as they get out of the scope? Is that what would happen, if you didn't dispose them manually? Is it the delay that makes people do this manually?

推荐答案

是的,你必须处理它们 - 不仅仅是画笔和画刷,而且位图图形

Yes, you have to dispose them - not just pen and brush, but also Bitmap and Graphics.

他们没有得到处理时,他们超出范围,因为变量本身引用,而不是对象,和C#编译器不知道的所有权是否还属于那些引用或没有(如 FillEllipse函数,在理论上,还记得它给出的参考,并尝试使用它在以后的某个时刻 - !记住,语言编译器没有库语义的任何专业知识)

They don't get disposed when they're out of scope because the variables themselves are references, not objects, and C# compiler doesn't know whether the ownership still belongs to those references or not (e.g. FillEllipse could, in theory, remember the reference it's given, and try to use it at some later moment - remember that language compiler doesn't have any special knowledge of library semantics!).

如果你想表明所有权限制在该范围内,可以使用使用语句:

If you want to indicate that ownership is restricted to that scope, you use the using statement:

using (Bitmap bmp = new Bitmap ( 100, 100 ))
using (Graphics g = Graphics.FromImage ( bmp ))
using (Pen p = new Pen ( Color.FromArgb ( 128, Color.Blue ), 1 ))
using (Brush b = new SolidBrush ( Color.FromArgb ( 128, Color.Blue ) ))
{
    g.FillEllipse ( b, 0, 0, 99, 99 );    
    g.FillRegion ( b, pictureBox1.Region );
}

这会根据需要自动使编译器插件调用处置,以确保所有的对象都设置一次,相应的使用范围左(是否正常,通过控制转移,如返回破发,或异常)。

This will make the compiler insert calls to Dispose automatically as needed, ensuring that all objects are disposed once the corresponding using scope is left (whether normally, by control transfer such as return or break, or an exception).

如果您有C ++背景,使用在C#中直接类似于一个常量性病:: auto_ptr的 ,不同之处在于它是一个语言结构这里,并且只能用于本地变量​​(即不为类字段)。

If you come from a C++ background, using in C# is directly analogous to a const std::auto_ptr, except that it's a language construct here, and can only be used for local variables (i.e. not for class fields).

这篇关于如果是必要的处置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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