C#的using语句

C#’s using statement provides a syntactic shortcut for calling Dispose on
objects that implement IDisposable, using a try/finally block. For example:
C#的using语句提供了调用Dispose on的语法快捷方式, 相当于使用try/finally块实现IDisposable的对象。例如:

using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{
	// ... Write to the file ...
}
// The compiler converts this to 编译器会将上述语句转换为:
FileStream fs = new FileStream ("myFile.txt", FileMode.Open);
try
{
	// ... Write to the file ...
}finally
{
	if (fs != null) ((IDisposable)fs).Dispose();
}

The finally block ensures that the Dispose method is called even when an
exception is thrown,1 or the code exits the block early.

finally块确保可以执行到Dispose方法,即使在try中抛出异常或代码提前return出来。
上述来源:C#_7.0 in a Nutshell

个人更倾向于使用using,
可以少写try…cath…的嵌套,还不用手动释放资源,避免手动释放前的操作抛异常执行不到释放语句,导致句柄或者文件流没释放,后续使用报文件占用之类的异常:

try{
using (FileStream fs = new FileStream ("myFile.txt", FileMode.Open))
{
	// ... Write to the file ...
}
}catch (Exception ex)
{
    //这里可以避免FileStream fs = new FileStream ("myFile.txt", FileMode.Open)抛出异常
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值