为什么ByRef不能与WithEvents一起使用?
我认为我对VB中的 ByVal
和 ByRef
有什么区别,但是我问题是当我尝试将其与用 WithEvents
声明的成员一起使用时。
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
.
我有以下内容方法:
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
但是在调用 SafeCloseAndDeRefConnection
之后, Connection
变量为 not 设置为 Nothing
并仍然具有其原始引用。
But after the call to SafeCloseAndDeRefConnection
the Connection
variable is not set to Nothing
and still has its original reference.
如果我删除 WithEvents
关键字对 SafeCloseAndDeRefConnection
的调用按预期进行(但显然无法处理事件)
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?
PS我在其他地方找到了类似的问题,但是解决方法在我的情况下不起作用。
P.S. I have found a similar question elsewhere, but the workaround does not work in my scenario.
也许调用:
Set Connection = Nothing
在之后SafeCloseAndDeRefConnection(Connection)
这将强制破坏对象,而不依靠VB6为您完成!
This will force the destruction of the object and not rely on VB6 to do it for you!