C#"使用"句法 [英] C# "Using" Syntax

查看:173
本文介绍了C#"使用"句法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用捕捉异常或把它?即

Does the using catch the exception or throw it? i.e.

using (StreamReader rdr = File.OpenText("file.txt"))
{
 //do stuff
}

如果该StreamReader的抛出一个异常,它是用抓或异常,所以调用这个函数可以处理呢?

If the streamreader throws an exception is it caught by using or thrown so the calling function can handle it?

推荐答案

using语句不要吃例外。

using statements do not eat exceptions.

所有的使用确实是你的范围,对象与使用块,并自动调用对象的Dispose(),当它离开该块。

All "Using" does is scope your object to the using block, and automatically calls Dispose() on the object when it leaves the block.

有一个疑难杂症虽然,如果一个线程被强制由外部源中断,它是可能的处置将永远不会被称为

There is a gotcha though, if a thread is forcefully aborted by an outside source, it is possible that Dispose will never be called.

这篇关于C#"使用"句法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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