为什么ByRef不能与WithEvents一起使用?

Fra*_*Nel 5 vb6 byref

我想我有一个相当好的想法ByVal,ByRef在VB 和VB 之间有什么区别,但我的问题是当我尝试将它与声明的成员一起使用时WithEvents.

我有以下方法:

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
Run Code Online (Sandbox Code Playgroud)

如果我有一个类成员声明如此:

Private WithEvents Connection As ADODB.Connection
Run Code Online (Sandbox Code Playgroud)

然后我想关闭连接然后调用它:

SafeCloseAndDeRefConnection Connection
Run Code Online (Sandbox Code Playgroud)

但之后该呼叫SafeCloseAndDeRefConnectionConnection变量设置Nothing,仍然有其原有的参考.

如果我删除WithEvents关键字,则调用SafeCloseAndDeRefConnection按预期工作(但显然事件无法处理)

任何人都可以向我解释为什么会这样吗?

PS我在其他地方发现了类似的问题,但解决方法在我的方案中不起作用.

Mik*_*eir 1

也许可以打电话:

Set Connection = Nothing
Run Code Online (Sandbox Code Playgroud)

SafeCloseAndDeRefConnection(Connection)

这将强制销毁对象,而不是依赖 VB6 来为您完成!

  • 有点违背了该方法最初存在的目的。 (3认同)