我看到这个:
using (StreamWriter sw = new StreamWriter("file.txt"))
{
// d0 w0rk s0n
}
我试图找到的所有信息都没有解释这是做什么的,而是给了我关于命名空间的东西。
您想查看using 语句的文档(而不是关于命名空间的using 指令)。
基本上这意味着该块被转换为try
/finally
块,并sw.Dispose()
在 finally 块中被调用(带有适当的空值检查)。
您可以在处理类型实现的任何地方使用 using 语句IDisposable
- 通常您应该将它用于您负责的任何一次性对象。
关于语法的一些有趣的部分:
您可以在一个语句中获取多个资源:
using (Stream input = File.OpenRead("input.txt"),
output = File.OpenWrite("output.txt"))
{
// Stuff
}
您不必分配给变量:
// For some suitable type returning a lock token etc
using (padlock.Acquire())
{
// Stuff
}
你可以不用大括号嵌套它们;方便避免缩进
using (TextReader reader = File.OpenText("input.txt"))
using (TextWriter writer = File.CreateText("output.txt"))
{
// Stuff
}
using 构造本质上是一个语法包装器,围绕在 using 中的对象上自动调用 dispose。例如,您上面的代码大致翻译成以下
StreamWriter sw = new StreamWriter("file.text");
try {
// do work
} finally {
if ( sw != null ) {
sw.Dispose();
}
}
规范的第 8.13 节回答了您的问题。
给你:http: //msdn.microsoft.com/en-us/library/yh598w02.aspx
基本上,它会在 using 范围的末尾自动调用 IDisposable 接口的 Dispose 成员。
检查这个使用语句