Skip to content

cCollection 属性参考

📋 属性列表

属性类型读写说明
ItemVariant读写获取或设置元素(默认属性)
RawCollectionCollection只读获取底层 Collection 对象

📦 Item 属性(默认属性)

说明

获取或设置集合中的元素。这是默认属性,可以直接使用 col("key") 语法。

支持通过 Key(字符串)或 Index(数字,从1开始)访问。

语法

vb
' Get
Property Get Item(ByVal KeyOrIndex As Variant) As Variant

' Let(值类型)
Property Let Item(ByVal KeyOrIndex As Variant, ByVal Value As Variant)

' Set(对象类型)
Property Set Item(ByVal KeyOrIndex As Variant, ByVal Value As Object)

参数

参数类型说明
KeyOrIndexVariantKey(字符串)或 Index(数字,从1开始)
ValueVariant/Object要设置的值

使用示例

获取元素

vb
Dim col As New cCollection
col.Add "张三", "user1"
col.Add "李四", "user2"

' 通过 Key 获取(显式写法)
Dim name As String
name = col.Item("user1")

' 简写形式(利用默认属性)
name = col("user1")

' 通过 Index 获取(从1开始)
name = col(1)  ' 获取第一个元素

设置元素(值类型)

vb
' 通过 Key 更新(如果 Key 不存在则添加)
col.Item("user1") = "张三-更新"

' 简写形式
col("user1") = "张三-更新"

' 通过 Index 更新(需要对应位置已有元素)
col(1) = "新值"

设置元素(对象类型)

vb
Dim col As New cCollection

' 添加对象
col.Add CreateObject("Scripting.Dictionary"), "dict1"

' 使用 Set 更新对象
Dim newDict As Object
Set newDict = CreateObject("Scripting.Dictionary")
newDict.Add "key", "value"

Set col("dict1") = newDict

遍历集合

vb
' For Each 遍历(利用 NewEnum)
Dim item As Variant
For Each item In col
    Debug.Print item
Next

' 通过索引遍历
Dim i As Long
For i = 1 To col.Count
    Debug.Print col(i)
Next

' 通过 Keys 遍历
Dim keys() As String
keys = col.Keys()
Dim key As Variant
For Each key In keys
    Debug.Print key & " = " & col(CStr(key))
Next

⚠️ 注意事项

  1. 索引从1开始:与 VB Collection 一致,索引从1开始
  2. Key 不存在时:获取会返回 Empty,设置会添加新元素
  3. 对象处理:获取对象时需要使用 Set 关键字

📦 RawCollection 属性

说明

获取底层的原始 Collection 对象。用于需要直接操作 Collection 的高级场景。

语法

vb
Property Get RawCollection() As Collection

返回值

Collection - 底层的 VB Collection 对象

使用示例

vb
' 获取底层 Collection
Dim rawCol As Collection
Set rawCol = col.RawCollection

' 直接使用 Collection 的方法
' 注意:直接操作 rawCol 不会同步 m_Keys,谨慎使用
Dim count As Long
count = rawCol.Count

⚠️ 注意事项

直接操作 RawCollection 可能导致 Keys 集合不同步,建议仅在读取场景使用。


📌 属性使用场景总结

常见访问模式

vb
Dim col As New cCollection
col.Add "张三", "user1"

' 推荐:通过 Key 访问
Debug.Print col("user1")

' 通过 Index 访问(知道位置时)
Debug.Print col(1)

' 安全访问(先检查存在)
If col.Exists("user1") Then
    Debug.Print col("user1")
End If

对象处理

vb
' 存储对象
col.Add SomeObject, "obj1"

' 读取对象(必须使用 Set)
Dim obj As MyClass
Set obj = col("obj1")

' 更新对象(必须使用 Set)
Set col("obj1") = NewObject

最后更新: 2026-05-17

VB6及其LOGO版权为微软公司所有