(1)字典定义与实例化
(1-1)字典的前期绑定(静态绑定)
工具——>引用
声明字典变量并实例化
'NO1:先声明,后实例化
Dim pDicX As Dictionary
Set pDicX = New Dictionary
'NO2:直接声明实例化,相当于执行了NO1的两句代码
Dim pDicX As New Dictionary
(1-2)字典的后期绑定(动态绑定)
Dim pDicX As Object
Set pDicX = CreateObject("Scriping.Dictionary")
(2)字典对象的基本操作
(2-1)字典的增【习惯:先判断键是否存在,再添加键值对】
'语法:Dictionary.Add (Key.Item),注意关键字【Key】值唯一,值可以重复
'作用:添加一个新的关键字及项目到字典中
'例子:我想给字典新增三个值,分别表示狗、猫、兔子有几条腿,
'【"dog",4,"cat":4,"rabbit":2】
Dim pStrX As String
pStrX = "dog"
If Not pDicX.Exists(pStrX) Then pDicX.Add pStrX, 4
pStrX = "cat"
If Not pDicX.Exists(pStrX) Then pDicX.Add pStrX, 4
pStrX = "rabbit"
If Not pDicX.Exists(pStrX) Then pDicX.Add pStrX, 2
(2-2)字典的查、改【习惯:先判断键是否存在,再查改】
'语法:Dictionary.Exists(Key) as Boolean
'作用:确定给定的关键字是否存在于字典中,存在返回true,不存在返回false
'语法:Dictionary.Item(Key)或者Dictionary(Key)
'作用:设置/获得给定关键字的项目
'语法:Dictionary.Key(Key)=newKey
'作用:更改关键字,将Key更改为newKey
'语法:Dictionary.Count As Long
'作用:获得字典中项目的个数
'例子:查询dog有几条腿,修改dog的腿数
pStrX = "dog"
If pDicX.Exists(pStrX) Then
'(2-2-1)查询键对应的值
Debug.Print Replace("写法一:dog有%条腿", "%", pDicX.item(pStrX)) ' 写法一:dog有4条腿
Debug.Print Replace("写法二:dog有%条腿", "%", pDicX("dog")) '写法二:dog有4条腿
'(2-2-2)修改键对应的值
pDicX.item(pStrX) = 4 '或者pDicX("dog") = 4
'(2-2-3)修改键本身的键名
pDicX.key("dog") = "dog123" '将关键字为"dog"更名为"dog123"
'(2-2-4)修改键本身的键名
Debug.Print pDicX.Count'3
End If
'语法:Dictionary.Keys
'作用:获得一个包含字典中所有关键字的数组。
'例子:如pDicX.Keys返回的数组是Array("dog", "cat", "rabbit"),切记数组返回的是变体类型Variant
'语法:Dictionary.Items
'作用:获得一个包含字典中所有项目的数组。
'例子:如pDicX.Keys返回的数组是Array(4,4,2),切记数组返回的是变体类型Variant
(2-3)字典的遍历
Dim i As Long, aryKey As Variant, aryItem As Variant
aryKey = pDicX.keys
aryItem = pDicX.Items
For i = 0 To pDicX.Count - 1
Debug.Print aryKey(i) & ":" & aryItem(i)
Next
'dog123:4
'cat:4
'rabbit:2
Dim vKey As Variant
For Each vKey In pDicX
Debug.Print vKey
Next
'dog123
'cat
'rabbit
(2-4)字典的删【习惯:先判断键是否存在,再删除】
'语法:Dictionary.Remove (Key)
'作用:从字典中删除给定的关键字【Key】
'例子:从字典pDicX中移除dog
pStrX = "dog"
If pDicX.Exists(pStrX) Then pDicX.Remove (pStrX)
'语法:Dictionary.RemoveAll
'作用:从字典中删除所有信息
pDicX.RemoveAll '仅仅是删除字典中的所有信息,字典对象并没有释放,有别于set pDicX = nothing
(2-5)字典对象的销毁
'对于对象的使用,虽然VB6有内在的变量销毁机制,但是我还是建议,在使用过后,最好是手动销毁,这是一种良好的编程习惯。
Set pDicX = Nothing