在 Class 中管理集合

Managing Collections inside a Class

我正在尝试使用 vba 中的 classes,但我没有找到任何与管理对象内部对象相关的文档,例如 class 中的数组或集合.

假设我有一个 class 人和一个 class 地址,我想管理一个人的地址。

地址

Private pStreet as String
Private pZip as Int

Public Property Let Street(val As String)
    pStreet = val
End Property
Public Property Get Street() As String
    Street = pStreet
End Property
Public Property Let Zip(val As String)
    pZip = val
End Property
Public Property Get Zip() As String
    Zip = pZip
End Property

Private pName As String
Private pSurname As String
Private pAddresses As Collection

Public Property Let Name(val As String)
    pName = val
End Property
Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Surname(val As String)
    pSurname = val
End Property
Public Property Get Surname() As String
    Surame = pSurname
End Property

Private Sub Class_Initialize()
    Set pAddresses = New Collection
End Sub
Private Sub Class_Terminate()
    Set pAddresses = Nothing
End Sub

Public Sub addAddress(ByVal val As Address)
    pAddresses.Add val
End Sub
Public Property Get Addresses() As Collection
    Set Addresses = pAddresses
End Property
Public Property Get Address(ByVal Index As Long) As Address
    Set Address = pAddresses(Index)
End Property

模块 1

Sub test()

Dim x As Person
Set x = New Person
Dim a1 As Address
Set a1 = New Address
Dim a2 As Address
Set a2 = New Address

x.Name = "Mark"
x.Surname = "Doe"
a1.Street = "first avenue 213"
a1.Zip = "41242"
a2.Street = "second avenue 213"
a2.Zip = "55242"
x.addAddress a1
x.addAddress a2

Debug.Print x.Address(0)

End Sub

我应该如何处理人class内部的地址集合? 例如,我如何检索集合的所有地址或第二个地址? x.addresses(1) 无效。

Person class 应该保存一组地址,以避免扩展和保留数组。一旦 class 为 initialized/terminated,集合应为 initialized/terminated。

看例子:

Private pAddresses as Collection

Private Sub Class_Initialize()
    Set pAddresses = New Collection
End Sub

Private Sub Class_Terminate()
    Set pAddresses = Nothing
End Sub

class 可以通过 属性 循环公开整个地址集合,或通过索引访问单个地址。

Public Property Get Addresses() As Collection
    Set Addresses = pAddresses 
End property

Public Property Get Address(ByVal Index As Long) As Address
    Set Address = pAddresses(Index)
End property

然后你可以循环:

Dim p As Person, a As Address

For Each a In p.Addresses
    a.Zip = ...
Next

或者通过索引获取单个地址:

Set a = p.Addresses(1)

最后,一个简单的Add方法,给这个人添加地址:

Public Sub AddAddress(ByVal param As Address)
    pAddresses.Add param
End Sub

您还可以通过提供地址对象和索引来使用 属性 添加(或替换)地址,但我不知道它对您的情况有多大用处。当然你需要确保索引是有效的。

Public Property Let Address(ByVal Index As Long, ByVal param As Address)
    pAddresses.Add param, Index
End property

然后调用它:

p.Addresses(Index) = a

要强制使用 Set 关键字,因为我们正在处理对象,请将 Let 更改为 Set。然后,你需要 set-it:

Set p.Addresses(Index) = a