为什么我的递归朋友函数在VB6中不起作用?

时间:2016-05-03 12:59:57

标签: vb6 friend-function

我在VB6中有一个递归函数,我希望函数是一个友元函数,所以我无法从任何地方到达它,但它不起作用。它只会说对象不存在,如果我将函数更改为公共函数它将起作用。为什么?我误解了朋友的功能是如何运作的?

代码如下所示:

Friend Function TestFunction() As Boolean
On Error GoTo ErrHandler

  TestFunction= False

  If Me.Works Then
    TestFunction= True
  End If

  If TestFunction = False And Me.HaveChild = True Then
    Dim objClass
    For Each objClass In Me.colChild 
      If objClass.TestFunction = True Then 'I get the break here, due to missing object
        TestFunction = True
        Exit For
      End If
    Next
  End If

  Exit Function

ErrHandler:
  Call LogError()
End Function

如果我只是将功能更改为公共功能,那么有人可以解释原因吗?

1 个答案:

答案 0 :(得分:4)

它不仅限于递归。这是一个最小的例子,它显示了没有递归的相同行为。

Option Explicit

Private Sub Form_Load()
    Dim objClass
    Set objClass = Me
    ' OK
    objClass.TestPublicFunction
    ' Run-time error '438': Object doesn't support this property or method
    objClass.TestFriendFunction
    End
End Sub

Public Sub TestPublicFunction()
    MsgBox "In public!"
End Sub

Friend Sub TestFriendFunction()
    MsgBox "In friend!"
End Sub

原因是即使在同一个项目中,也无法在后期绑定的对象上调用Friend属性和方法。见this MSDN article

  

重要因为朋友成员不属于对象的公开   接口,他们无法访问后期绑定 - 即通过   变量声明为Object。要使用好友成员,您必须申报   具有早期绑定的变量 - 即As classname。

实际上,您应该能够通过明确声明每个循环迭代器来修复代码,而不是隐式使用Variant。

Dim objClass As ClassName
For Each objClass In Me.colChild 
相关问题