我正在VBA中创建不可变链接列表类。它提供了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 sequenceGet NewEnum,它正确地构建了集合,然后返回Copy并在不执行任何迭代且没有错误之后退出循环。我唯一的猜测是NewEnum是一个变量的迭代器,该变量在退出Get NewEnum时将被销毁。
那是怎么回事吗?

最佳答案

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]值。

关于vba - 无法在VBA中创建新的枚举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26721017/

10-11 09:31