我有一个类,我已经声明了一个FileStream和一个StreamReader:
选项严格关闭 选项明确的
Friend Class clsFileReader
Private _fs As IO.FileStream
Private _sr As IO.StreamReader
我想问我是否明确需要关闭这些:
Protected Overrides Sub Finalize()
_fs.Close()
_sr.Close()
End Sub
...或者如果这是自动完成的。
感谢您的帮助!
ps:我不能使用"使用"因为我想逐行读取文件:
Public Function ReadLine() As String
Debug.Assert(Not _sr.EndOfStream)
_sCurrentLineString = _sr.ReadLine
_iCurentLineIndex = _iCurentLineIndex + 1
Return _sCurrentLineString
End Function
答案 0 :(得分:1)
我建议您使用与流中相同的功能。完成IDisposable界面并在完成后对类实例调用.Dispose。与您对流的处理方式相同。
这是一个简单的例子。
Class clsFileReader : Implements IDisposable
Private _fs As IO.FileStream
Private _sr As IO.StreamReader
' Flag: Has Dispose already been called?
Dim disposed As Boolean = False
' Public implementation of Dispose pattern callable by consumers.
Public Sub Dispose() _
Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
' Protected implementation of Dispose pattern.
Protected Overridable Sub Dispose(disposing As Boolean)
If disposed Then Return
If disposing Then
' Free any other managed objects here.
'
_fs.Close()
_sr.Close()
End If
' Free any unmanaged objects here.
'
disposed = True
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
End Sub
End Class