前段时间在项目验收的过程中,验收人员提到了打开数据库使用完毕之后有没有及时关闭,然后就打开代码看了一眼,没有Close()方法呢。在检查过程中发现,虽然没有直接使用Close()方法,但在执行连接数据库时使用了using关键字,然后验收人员便说没有问题 。为什么没有使用Close()方法,仅有using关键字也是可以的呢?于是上网查了相关的资料,发现大家说的都是大同小异的,不清楚大家说的是不是都有道理,还有正确性如何。有那么一瞬间想到了纪老师提到的API文档,于是就想看看官方到底是如何解释的,来验证一下网上说的。下面是官方的解释:
The using keyword has three major uses:
三个主要的用法:
NO1:The using statement defines a scope at the end of which an object will be disposed.
NO2:The using directive creates an alias for a namespace or imports types defined in other namespaces.
NO3:The using static directive imports the members of a single class.
NO1:
Provides a convenient syntax that ensures the correct use of IDisposable objects.
Example:
The following example shows how to use the using statement.
using (var font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
Remarks
File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.
When the lifetime of an IDisposable objec