创建一个带有using块的XmlWriter是否足够(没有调用Close()),还是最好使用try/finally块,并在finally中调用Close()?
创建一个带有using块的XmlWriter是否足够(没有调用Close()),还是最好使用try/finally块,并在finally中调用Close()?
using 块是一个快捷方式,它相当于使用 try/finally 块,并在任何实现 IDisposable 接口的对象上调用 Dispose()。
对于流和流编写器,Dispose() 通常手动调用 Close()。使用反射器,以下是 XmlWriter 的 Dispose 方法:
protected virtual void Dispose(bool disposing)
{
if (this.WriteState != WriteState.Closed)
{
try
{
this.Close();
}
catch
{
}
}
}
那么简短的回答是,是的,using
块将为您处理关闭 XmlWriter 的操作。
但是...
在 XmltTextWriter.Close() 上使用 Reflector 显示:
如果 (this.closeOutput) { this.stream.Close(); } this.Stream = null;
closeOutput 标志设置为 settings.CloseOutput,它可以是 false。
当使用 "using" 表达式在 XmlTextWriter 上时,您确定处理程序是否释放?