问题
I think I have a fairly good idea what the difference is between ByVal
and ByRef
in VB, but my issue is when I try using it in conjunction with a member that is declared with WithEvents
.
I have the following method:
Private Sub SafeCloseAndDeRefConnection(ByRef cnx As ADODB.Connection)
On Error GoTo ErrH
If Not cnx Is Nothing Then
If (cnx.State And adStateConnecting) = adStateConnecting Then
cnx.Cancel
End If
If (cnx.State And adStateOpen) = adStateOpen Then
cnx.Close
End If
Set cnx = Nothing
End If
Exit Sub
ErrH:
Set cnx = Nothing
End Sub
If I have a class member declared as such:
Private WithEvents Connection As ADODB.Connection
I then want to close the connection and then call it as such:
SafeCloseAndDeRefConnection Connection
But after the call to SafeCloseAndDeRefConnection
the Connection
variable is not set to Nothing
and still has its original reference.
If I remove the WithEvents
keyword the call to SafeCloseAndDeRefConnection
works as expected (but obviously events can then not be handled)
Can anyone explain to me why this is happening?
P.S. I have found a similar question elsewhere, but the workaround does not work in my scenario.
回答1:
Perhaps call:
Set Connection = Nothing
After SafeCloseAndDeRefConnection(Connection)
This will force the destruction of the object and not rely on VB6 to do it for you!
来源:https://stackoverflow.com/questions/17468597/why-does-byref-not-work-in-conjunction-with-withevents