2
我正在查看传统的VB6应用程序,并试图了解VB6集合如何工作。使用Collection.Add方法,我发现该集合刚刚存在其最后添加的选项,重复。 例如如果我将1,2,3,4和5添加到集合中,我会将5,5,5,5和5作为集合内容返回。VB6:如何正确地存储集合中的类对象?
在我的测试案例中,我有一个封装类模块,EncapsulationClass.cls存储一些简单的字符串。它的实现:
Option Explicit
'ivars
Private pEntityId As String
Private pEntityName As String
'properties
'pEntityId
Public Property Get entityId() As String
Let entityId = pEntityId
End Property
Private Property Let entityId(ByVal inEntityId As String)
Let pEntityId = inEntityId
End Property
'pEntityName
Public Property Get entityName() As String
Let entityName = pEntityName
End Property
Private Property Let entityName(ByVal inEntityName As String)
Let pEntityName = inEntityName
End Property
'constructor
Public Sub init(ByVal inEntityId As String, ByVal inEntityName As String)
Let entityId = inEntityId
Let entityName = inEntityName
End Sub
我想这些多个实例存储在一个迭代的对象,所以我用一个集合。
在我的测试情况下,我有这个简单的功能:
Private Function getACollection() As Collection
Dim col As New Collection
Dim data(0 To 5) As String
data(0) = "zero"
data(1) = "one"
data(2) = "two"
data(3) = "three"
data(4) = "four"
data(5) = "five"
For Each datum In data
Dim encap As New EncapClass
encap.init datum, datum & "Name"
col.Add encap
Next
'return
Set getACollection = col
End Function
该功能,然后在下面的简单的逻辑用于:
Private Sub Form_Load()
Dim col As Collection
Set col = getACollection()
For Each i In col
Debug.Print i.entityId, i.entityName
Next i
End Sub
我希望可以将输出为:
one oneName
two twoName
three threeName
four fourName
five fiveName
但是,我只是重复了最后一个添加的元素,五次。
five fiveName
five fiveName
five fiveName
five fiveName
five fiveName
有没有我缺少的东西,在句法上?通过各种books查看,集合被添加了Add方法,并按预期工作。
'getACollection'缺少return语句的一两件事, – Plutonix
编辑:你是正确的我没有粘贴正确! – Tony