[英]Calling close on passed in member StringWriter to XMLTextWriter
I found some code that was not correctly wrapping XMLTextWriter and StringWriter with the using clauses. 我发现一些代码没有使用using子句正确包装XMLTextWriter和StringWriter。 As I'm correcting it, I stumbled on a interesting question:
在纠正时,我偶然发现了一个有趣的问题:
do I have to explicitly add calls to Close() on each writer or does XMLTextWriter handle calling Close() on StringWriter instance automatically? 我是否必须在每个编写器上显式添加对Close()的调用,或者XMLTextWriter是否自动处理StringWriter实例上的调用Close()?
using (StringWriter stringWriter = new StringWriter(sb))
{
using (XmlTextWriter writer = new XmlTextWriter(stringWriter))
{
writer.Flush();
writer.Close();
}
// is stringWriter.Close(); required here?
}
Thnx Matt Thnx马特
Usually it is not required if the class in your using
statement implements IDisposable
correctly (in this case if StringWriter
and XmlTextWriter
call their Close
methods in the Dispose
method implementation). 通常,如果
using
语句中的类正确实现IDisposable
(在这种情况下,如果StringWriter
和XmlTextWriter
在Dispose
方法实现中调用其Close
方法),则不需要该类。
At the end of a using
block the Dispose
method will automatically be called. 在
using
块的末尾,将自动调用Dispose
方法。
From the Reference Source of the XmlTextWriter.cs class you can see the following line in the Close()
method 从XmlTextWriter.cs类的“ 引用源”中,您可以在
Close()
方法中看到以下行:
textWriter.Close();
where the textWriter
was received in constructor, so the answer to your question is that you don't need to call the Close()
method on your StringWriter
instance, but doing so will do no harm. 在构造函数中接收到
textWriter
,因此,对您的问题的答案是,您无需在StringWriter
实例上调用Close()
方法,但这不会造成任何危害。
For more info about IDisposable
check out this link . 有关
IDisposable
更多信息,请查看此链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.