我在VBA中创建一个Immutable Linked List类。它提供了ToArray
和ToCollection
方法,我已将其验证为有效。但是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
时被销毁。
那是怎么回事?
答案 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]
值。