我在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
如果我只是将功能更改为公开功能,它将起作用,有人可以解释原因吗?
它不仅限于递归。这是一个最小的示例,它显示了没有递归的相同行为。
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属性和方法。看到这篇MSDN文章:
重要说明:由于Friend成员不是对象公共接口的一部分,因此不能后期绑定(即,通过声明为Object的变量)访问它们。要使用Friend成员,必须声明具有早期绑定的变量,即As类名。
因此,实际上,您应该能够通过显式声明每个循环迭代器而不是隐式使用Variant来修复代码。
Dim objClass As ClassName
For Each objClass In Me.colChild
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句