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

时间:2014-01-21 16:35:20

标签: vba vb6

我正在寻找一个传统的VB6应用程序,并试图了解VB6 Collections的工作原理。使用 Collection.Add 方法,我发现该集合只是存在其最后添加的选项,重复。 e.g。如果我将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

我想在可迭代对象中存储这些实例,因此我使用了 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

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

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方法,并按预期工作。

1 个答案:

答案 0 :(得分:6)

缺少set实际上是在重用encap的同一单个实例,因此循环内的更改会修改集合中已有的单个重复引用。

修复:

 Dim encap As EncapClass

 For Each datum In data
     set encap = New EncapClass
     encap.init datum, datum & "Name"
     col.Add encap
 Next