为什么ByRef不能与WithEvents一起使用? [英] Why does ByRef not work in conjunction with WithEvents?

查看:129
本文介绍了为什么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!

这篇关于为什么ByRef不能与WithEvents一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆