'使用'是否仍然以这种方式工作? [英] Does 'using' still work right this way?
本文介绍了'使用'是否仍然以这种方式工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
private void SomeFunction()
{
使用(StreamReader sr = new StreamReader( C:\\File.txt))
{
if (someCondition)
{
return ;
}
}
}
也许是一个愚蠢的问题...
但是,如果return语句跳出函数,文件是否仍会关闭?
解决方案
当然,它会正常工作。
使用use严格等同于带有sr.Dispose()
在finally
块中。使用语句的只是语法糖( http ://en.wikipedia.org/wiki/Syntax_sugar [ ^ ])。
private void SomeFunction()
{
StreamReader sr = new StreamReader( C:\\File.txt);
尝试 {
如果(someCondition)
返回跨度>;
} 最后 {
sr.Dispose(); // 在使用语句
} $ b的结束'}'上发生相同的情况$ b}
请参阅: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx [ ^ ]。
-SA
是的,文件将被关闭,并且无论发生什么情况,都将处理using语句中的所有资源。
请参阅microsoft文章:
http://msdn.microsoft.com/en-gb/library/yh598w02.aspx [ ^ ]
问候
Jegan
是。使用ILdasm检查产生的IL。提示:生成一个''finally''子句,其中包含读者Dispose()的代码。
private void SomeFunction() { using (StreamReader sr = new StreamReader("C:\\File.txt")) { if (someCondition) { return; } } }
Maybe a stupid question...
But does the file still get closed given that the return statement jumps out of the function?解决方案Of course, it will work properly.
[EDIT]
The use of using is strictly equivalent to analogous try-finally statement withsr.Dispose()
in thefinally
block. Theusing
statement is just a syntax sugar (http://en.wikipedia.org/wiki/Syntax_sugar[^]).
private void SomeFunction() { StreamReader sr = new StreamReader("C:\\File.txt"); try { if (someCondition) return; } finally { sr.Dispose(); // same happens "on the closing '}' of using statement" } }
Please see: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.80%29.aspx[^].
—SA
Hi,
Yes,the file will be closed, and all the resources inside the using statement will be disposed regardless of what happens.
See microsoft article :
http://msdn.microsoft.com/en-gb/library/yh598w02.aspx[^]
Regards
Jegan
Yes. Use ILdasm to examine the IL produced. Hint: a ''finally'' clause is generated that includes the code to Dispose() of your reader.
这篇关于'使用'是否仍然以这种方式工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文