简体   繁体   English

调用关闭,将传入的StringWriter成员传递给XMLTextWriter

[英]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 (在这种情况下,如果StringWriterXmlTextWriterDispose方法实现中调用其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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM