RAII XmlWriter VisualBasic

时间:2016-03-26 05:09:29

标签: vb.net raii

我只是拿起VB,所以这可能是一个菜鸟问题。提前道歉。

我试图用一个类来包装一个XmlWriter来管理内存,刷新,关闭等等......这样客户就不用担心了。

我的代码是:

Option Explicit On
Option Strict Off

Imports System.Xml
Imports System.IO


Module MainModule
    Sub Main()
        Dim xmltest As XmlOutput = New XmlOutput("output.xml", "test")
        xmltest.writeData("hello", "19.95")
    End Sub
End Module

Public Class XmlOutput

    Private xmlWriter As XmlWriter

    Public Sub New(ByVal filename As String, ByVal calculator As String)
        xmlWriter = XmlWriter.Create(filename)
        xmlWriter.WriteStartDocument(True)
        xmlWriter.WriteStartElement(calculator)
    End Sub

    Protected Overrides Sub Finalize()
        xmlWriter.WriteEndElement()
        xmlWriter.WriteEndDocument()
        xmlWriter.Dispose()
    End Sub

    Public Sub writeData(ByVal head As String, ByVal value As String)
        xmlWriter.WriteElementString(head, value)
    End Sub
End Class

当我运行时,我收到以下错误:

System.ObjectDisposedException was unhandled
  HResult=-2146232798
  Message=Cannot access a closed file.
  ObjectName=""
  Source=mscorlib
  StackTrace:
       at System.IO.__Error.FileNotOpen()
       at System.IO.FileStream.Flush(Boolean flushToDisk)
       at System.IO.FileStream.Flush()
       at System.Xml.XmlUtf8RawTextWriter.Close()
       at System.Xml.XmlRawWriter.Close(WriteState currentState)
       at System.Xml.XmlWellFormedWriter.Close()
       at System.Xml.XmlWriter.Dispose(Boolean disposing)
       at System.Xml.XmlWriter.Dispose()
       at XmlOutputTest.XmlOutput.Finalize()
  InnerException: 

看起来XmlWriter在关闭XmlWriter之前关闭了FileStream。由于XmlWriter负责FileStream,我希望它知道FileStream何时关闭。

问题:

  1. 为什么XmlWriter试图关闭它已经关闭的东西(或者我可能错误地解释了堆栈跟踪)?
  2. 我需要做些什么来解决这个问题?

0 个答案:

没有答案