无法在VBA中创建新枚举

时间:2014-11-03 18:53:42

标签: vba

我在VBA中创建一个Immutable Linked List类。它提供了ToArrayToCollection方法,我已将其验证为有效。但是Get NewEnum() As IUnknown属性不起作用,我不知道为什么。

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4

    Set NewEnum = ToCollection.[_NewEnum]

End Property

使用sequence作为SList使用调试程序逐步执行以下代码

Public Function Copy(ByVal sequence As Variant) As SList

    Dim made As New SList

    Dim element As Variant
    For Each element In sequence
       Set made = made.Cons(element)
    Next

    Set Copy = made.Reverse

End Function

显示For Each element In sequence调用Get NewEnum,它正确构建集合,然后返回Copy并在执行无迭代且没有错误后退出循环。我唯一的猜测是NewEnum是一个变量的迭代器,它在退出Get NewEnum时被销毁。 那是怎么回事?

1 个答案:

答案 0 :(得分:6)

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4

    Set NewEnum = ToCollection.[_NewEnum]

End Property

ToCollection每次调用时都会返回一个新集合;这可能会奏效:

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4

    Static internalCollection As Collection
    If internalCollection Is Nothing Then Set internalCollection = ToCollection

    Set NewEnum = internalCollection.[_NewEnum]

End Property

......但它相当难看。理想情况下,您需要一些实例级encapsulated As Collection来返回[_NewEnum]值。