问题: 在使用语句中将目标对象声明为 'Code snippet 1' 中所示,是否有优势?
'Code snippet 2' 和 'Code snippet 3' 片段在我看来也是有效的,但不确定第一个代码片段是否比其他两个具有更多的优势。
代码片段 1
using (TextWriter w = File.CreateText("log.txt")) {
w.WriteLine("This is line one");
w.WriteLine("This is line two");
}
代码片段 2
TextWrite w = null;
using (w = File.CreateText("log.txt")) {
w.WriteLine("This is line one");
w.WriteLine("This is line two");
}
代码片段 3
TextWriter w = File.CreateText("log.txt");
using (w) {
w.WriteLine("This is line one");
w.WriteLine("This is line two");
}
更新1:看起来“代码片段3”可能会导致在实例化TextWriter对象时第一行发生异常时资源没有被处理。因此,前两个代码片段在资源处理方面是等价的,而第三个代码片段绝对不建议使用,除非第三个代码片段有一个finally块,在该块中处理TextWriter对象的处理。
更新2:在得到Peter的答案后,我意识到我在更新1中的观察结果是不正确的。解释如下:如果在任何3个代码片段中的任何一个中实例化TextWriter时出现异常,则Dispose方法将永远不会被调用,因为没有TextWriter对象可以调用此方法。
using
块的范围之外访问w
。 - Mike Christensen