VB6:如何在集合中正确存储类对象?

ton*_*mke 2 vb6 vba

我正在寻找一个传统的VB6应用程序,并试图了解VB6 Collections如何工作.使用Collection.Add方法,我发现该集合只是存在其最后添加的选项,重复.例如,如果我将1,2,3,4和5添加到集合中,我将获得5,5,5,5和5作为集合内容.

在我的测试用例中,我有一个封装类模块,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
Run Code Online (Sandbox Code Playgroud)

我想在可迭代对象中存储这些实例,因此我使用了Collection.

在我的测试用例中,我有这个简单的功能:

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
Run Code Online (Sandbox Code Playgroud)

然后在以下简单逻辑中使用此函数:

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
Run Code Online (Sandbox Code Playgroud)

我希望输出为:

one oneName
two twoName
three threeName
four fourName
five fiveName
Run Code Online (Sandbox Code Playgroud)

但是,相反,我只是重复添加最后一个元素,重复五次.

five fiveName
five fiveName
five fiveName
five fiveName
five fiveName
Run Code Online (Sandbox Code Playgroud)

语法上有什么我缺少的东西吗?查看各种书籍,集合附加了Add方法,并按预期工作.

Ale*_* K. 6

缺少a set有效地重复使用相同的单个实例,encap因此循环内的更改会修改集合中已有的单个重复引用.

修理:

 Dim encap As EncapClass

 For Each datum In data
     set encap = New EncapClass
     encap.init datum, datum & "Name"
     col.Add encap
 Next
Run Code Online (Sandbox Code Playgroud)