【问题标题】:Why does not my recursive friend function work in VB6?为什么我的递归友元函数在 VB6 中不起作用?
【发布时间】:2016-05-03 12:59:56
【问题描述】:

我在 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

如果我只是将功能更改为公开它会起作用,有人可以解释为什么吗?

【问题讨论】:

  • 什么是 colChild?定义 TestFunction 的类型的对象的集合?
  • 是的,它是类对象的集合。

标签: vb6 friend-function


【解决方案1】:

不限于递归。这是一个最小的示例,它显示了相同的行为而无需递归。

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

重要因为朋友成员不是对象的公共部分 接口,它们不能被后期绑定访问——即通过 声明为对象的变量。要使用 Friend 成员,您必须声明 具有早期绑定的变量——即作为类名。

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

Dim objClass As ClassName
For Each objClass In Me.colChild 

【讨论】:

  • 实际上他在那里使用的是隐式创建的Variant,而不是Object - 但除了额外的开销之外几乎没有什么区别。
  • 好吧,我在 .net 上的时间太长了。固定。
猜你喜欢
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 2021-10-28
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
相关资源
最近更新 更多