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

Why does not my recursive friend function work in VB6?

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

代码如下所示:

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

如果我只是将函数更改为 public 它会起作用,有人可以解释为什么吗?

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

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:

Important Because Friend members aren't part of an object's public interface, they can't be accessed late bound — that is, through variables declared As Object. To use Friend members, you must declare variables with early binding — that is, As classname.

因此,实际上,您应该能够通过显式声明 for each 循环迭代器来修复代码,而不是隐式使用 Variant。

Dim objClass As ClassName
For Each objClass In Me.colChild