c# 中的 using 结构怎么样?
我看到了这一点:
using (StreamWriter sw = new StreamWriter("file.txt"))
{
// d0 w0rk s0n
}
我尝试查找信息的所有内容都没有解释它在做什么,而是为我提供了有关名称空间的内容。
I see this:
using (StreamWriter sw = new StreamWriter("file.txt"))
{
// d0 w0rk s0n
}
Everything I try to find info on is does not explain what this doing, and instead gives me stuff about namespaces.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您想要查看 using 语句< /a> (而不是关于命名空间的 using 指令)。
基本上,这意味着该块被转换为
try
/finally
块,并且在 finally 块中调用sw.Dispose()
(使用适当的无效检查)。无论何时处理实现 IDisposable 的类型,您都可以使用 using 语句 - 通常您应该将它用于您负责的任何一次性对象。
关于语法的一些有趣的地方:
您可以在一条语句中获取多个资源:
您不必分配给变量:
您可以不用大括号嵌套它们;方便避免缩进
You want to check out documentation for the using statement (instead of the using directive which is about namespaces).
Basically it means that the block is transformed into a
try
/finally
block, andsw.Dispose()
gets called in the finally block (with a suitable nullity check).You can use a using statement wherever you deal with a type implementing
IDisposable
- and usually you should use it for any disposable object you take responsibility for.A few interesting bits about the syntax:
You can acquire multiple resources in one statement:
You don't have to assign to a variable:
You can nest them without braces; handy for avoiding indentation
using 构造本质上是一个语法包装器,自动调用 using 中对象的 dispose。例如,您上面的代码大致翻译为以下内容
The using construct is essentially a syntactic wrapper around automatically calling dispose on the object within the using. For example your above code roughly translates into the following
规范第 8.13 节回答了您的问题。
Your question is answered by section 8.13 of the specification.
在这里:http://msdn.microsoft.com/en-us/ library/yh598w02.aspx
基本上,它会在 using 作用域末尾自动调用 IDisposable 接口的 Dispose 成员。
Here you go: http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Basically, it automatically calls the Dispose member of an IDisposable interface at the end of the using scope.
检查此使用声明
check this Using statement