我正在VBA中创建不可变链接列表类。它提供了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
时将被销毁。那是怎么回事吗?
最佳答案
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/