问题描述
在这段代码中,我预计 uTest1 函数中的 vCallLevel 变量将等于 1,并在退出时将其重置为 0。 但是,从函数返回时,它保留了它的值,当再次调用uTest1函数时,vCallLevel值再次增加1(析构函数中的MsgBox也没有被执行)。 这意味着在退出时不会调用 Protected Overrides Sub Finalize () 析构函数。 但是,当我关闭 Excel 时,我多次收到 MsgBox 消息。 我做错了什么?
{
Imports ExcelDna.Integration
Public Module Fun
Public vCallLevel As Double
Public Class tcLocal
Public Sub New()
vCallLevel = vCallLevel + 1
End Sub
Protected Overrides Sub Finalize()
vCallLevel = vCallLevel - 1
MsgBox(vCallLevel)
MyBase.Finalize()
End Sub
End Class
Public Function uTest1() As Double
Dim oLocal As New tcLocal
Return vCallLevel
End Function
End Module
}
我就是这样做的。无论如何都行不通...
Imports ExcelDna.Integration
Public Module Fun
Public vCallLevel As Double
Public Class tcLocal
Implements Idisposable
#Region "Idisposable Support"
Private disposedValue As Boolean
Protected Overridable Sub dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
vCallLevel = vCallLevel - 1
MsgBox(vCallLevel)
End If
End If
disposedValue = True
End Sub
Public Sub dispose() Implements Idisposable.dispose
dispose(True)
End Sub
Public Sub New()
vCallLevel = vCallLevel + 1
End Sub
#End Region
End Class
Public Function uTest1() As Double
Dim oLocal As New tcLocal
Return vCallLevel
End Function
End Module
其实我只需要在oLocal内部进行这些动作——退出uTest函数时的初始化和去激活:
Public vCallLevel As Double
Public Class tcLocal
Public Sub New ()
vCallLevel = vCallLevel + 1
End Sub
Public Sub "Called on exit from uTest function" ()
vCallLevel = vCallLevel - 1
End Sub
End Class
Public Function uTest1 () As Double
Dim oLocal As New tcLocal
Return vCallLevel
End Function
我正在尝试从 VBA 翻译我的代码,一个类中只有 2 个标准 SUB...
Private Sub Class_Initialize()
CallLevel = CallLevel + 1
End Sub
Private Sub Class_Terminate()
CallLevel = CallLevel - 1
End Sub
解决方法
以下是 VB.NET 中 IDisposable
的实现:
Public Class Fun
Implements IDisposable
#Region "IDisposable Support"
Private disposedValue As Boolean ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)
If Not disposedValue Then
If disposing Then
' TODO: dispose managed state (managed objects).
End If
' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
' TODO: set large fields to null.
End If
disposedValue = True
End Sub
' TODO: override Finalize() only if Dispose(disposing As Boolean) above has code to free unmanaged resources.
'Protected Overrides Sub Finalize()
' ' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
' Dispose(False)
' MyBase.Finalize()
'End Sub
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(disposing As Boolean) above.
Dispose(True)
' TODO: uncomment the following line if Finalize() is overridden above.
' GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
Public Function uTest1() As Double
Using oLocal As New tcLocal
Return vCallLevel
End Using
End Function