创建一个类模块,命名为MyCollection
代码如下:
- OptionExplicit
- PrivatecolKeyAsNewCollection
- PrivatecolValAsNewCollection
- PublicPropertyGetCount()AsLong
- Count=colKey.Count
- EndProperty
- PublicPropertyGetRealCol()AsCollection
- SetRealCol=colVal
- EndProperty
- PublicSubAdd(Item,OptionalKey,OptionalBefore,OptionalAfter)
- colKey.AddKey,Key,Before,After
- colVal.AddItem,After
- EndSub
- PublicSubRemove(index)
- colKey.Removeindex
- colVal.Removeindex
- EndSub
- PublicFunctiongetKey(index)AsString
- getKey=colKey.Item(index)
- EndFunction
下面我们用一些代码来测试一下collection特性是否保留,并且我们能不能通过索引号获得key
建个窗体,放个按钮
原文链接:/vb/260616.html
- PrivateSubCommand1_Click()
- DimaAsNewMyCollection'创建实例
- '加入对象
- a.Add"test1","key1"
- a.Add"test2","key2"
- a.Add"test3","key3"
- a.Add"test4","key4"
- a.Add"test5","key5"
- Debug.Print"用索引号方式获取对象"
- Debug.Printa.RealCol(2)
- Debug.Print"用key获取对象"
- Debug.Printa.RealCol("key3")
- Debug.Print"remove对象"
- a.Remove"key2"
- Debug.Print"foreach访问"
- Dimb
- ForEachbIna.RealCol
- Debug.Printb
- Next
- Debug.Print"罗列所有key"
- DimiAsInteger
- Fori=1Toa.Count
- Debug.Printa.getKey(i)
- Next
- Debug.Print"异常测试"
- a.Add"asdad","key5"'重复key
- a.Remove"key6"'删除不存在的对象
- a.getKey8'获取不存在的key
- EndSub