C#中using关键字的使用

本文介绍了C#中using关键字的用途,包括确保IDisposable对象的正确使用,以及using静态指令的三种用法:引入命名空间、访问类型静态成员和创建类型别名。using语句在确保异常处理时调用Dispose方法,并限制对象的作用域。using静态指令允许直接访问类型中的静态成员,提高了代码的简洁性。
摘要由CSDN通过智能技术生成
    前段时间在项目验收的过程中,验收人员提到了打开数据库使用完毕之后有没有及时关闭,然后就打开代码看了一眼,没有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

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值