对表单使用 dispose() 方法而不是 close() 方法 [英] Using dispose() method instead of close() method to a form

查看:21
本文介绍了对表单使用 dispose() 方法而不是 close() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 Dispose() 而不是 Close() 关闭使用 Show() 打开的表单时会发生什么>?谁能详细告诉我,Dispose() 方法中发生了什么?

What is happening when I close a form, which was opened using Show(), by using Dispose() instead of Close()? Can someone tell me in detail, what happening in the Dispose() method?

推荐答案

Close()Dispose() 的基本区别在于,当一个 Close() 方法被调用,任何被管理的资源都可以被暂时关闭并可以再次打开.这意味着,对于相同的对象,可以重新打开或使用资源.Dispose() 方法从内存中永久删除任何资源((非)托管的)以进行清理,并且该资源不再存在以供进一步处理.

The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

或者只是一个一般性的陈述.连接对象调用 Close() 会将连接释放回池中.调用Dispose()会调用Close(),然后将连接字符串设置为null.

Or just a general statement. With the connection object calling Close() will release the connection back into the pool. Calling Dispose() will call Close() and then set the connection string to null.

某些对象(例如 Stream)实现了 IDisposable,但是 Dispose 方法仅在您首先将对象强制转换为 IDisposable 时才可用.不过,它确实公开了一个 Close() 方法.

Some objects such as a Stream implement IDisposable but the Dispose method is only available if you cast the object to an IDisposable first. It does expose a Close() method though.

我总是认为,当您完成对象时,您应该在任何实现 IDisposable 的对象上调用 Dispose().即使它什么都不做.无论如何,jit 编译器都会从最终代码中优化它.如果对象包含 Close() 但没有 Dispose() 则调用 Close().

I would always argue that you should call Dispose() on any object that implements IDisposable when you are through with the object. Even if it does nothing. The jit compiler will optimize it out of the final code anyway. If the object contains a Close() but no Dispose() then call Close().

您也可以在 IDispoable 对象上使用 using 语句

You can also use the using statement on IDispoable objects

using(SqlConnection con = new SqlConnection())
{
    //code...
}

当块退出时,这将在 SqlConnection 上调用 Dispose().

This will call Dispose() on the SqlConnection when the block is exited.

这篇关于对表单使用 dispose() 方法而不是 close() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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