Why does ByRef not work in conjunction with WithEvents?

人走茶凉 提交于 2019-12-12 11:06:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!