获取Collection对象上的项的键 [英] Get the key of an item on a Collection object

查看:208
本文介绍了获取Collection对象上的项的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境是我推入集合的成员是无名的,不可识别的(避免坏的抽象,请不要怪异:成员实际上是其他集合实例)。
为了能够快速搜索,我为每个新成员创建一个有意义的哈希名称,并提供它作为Key字符串,在最顶层集合的添加方法。

The environment is that the members I'm pushing into the Collection are nameless, un-identifiable (to avoid bad abstractions, and please, don't freak out: members are actually other Collection instances). In order to be able to make fast searches, I'm creating a meaningfull hash name for each new member, and provide it as the Key string, on the Add method of the "topmost" Collection.

当我有一个键来搜索时,一切都是dandy ...
问题是我想迭代集合的成员,并获得提供的密钥添加(生成的Hash,不幸的是不可能反向哈希)。

When I have a key to seach with, everything's dandy... Problem is I'd like to iterate the members of the collection and get the Key that was provided on Add (the generated Hash, that unfortunetely is not possible to reverse-Hash).

我通过定义插入的子集合实例的第一个成员

I'm moving on by defining that the first member of the inserted sub-collection instance is a string, containing the mentioned hash, but if anyone cracks this, I'll be much obliged.

推荐答案

简单的方法将使用字典,而不是采集。字典本质上是一个关键,项目对的关联数组,并支持将其键作为数组检索。要使用字典,您需要添加对Microsoft脚本运行时的引用。使用字典的缺点是它不是枚举与集合相同的方式。更复杂的解决方案是将收集和字典封装以创建如下所述的可枚举字典。

The simple approach would be to use a Dictionary instead of a Collection. The Dictionary is essentially an associative array of key, item pairs and support retrieval of its keys as an array. To use the Dictionary you will need to add a reference to the Microsoft Scripting Runtime. The drawback to using the dictionary is that it is not enumerable in the same way as the collection. A more elaborate solution would be to wrap the collection and dictionary to create an enumerable dictionary as outlined below.

NB 要使NewEnum正常工作在VBA中,类模块必须导出并手动编辑,如下所示,然后重新导入。

NB To get NewEnum to work properly in VBA the class module has to be exported and manually edited as follows and then re-imported.

Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
   Set NewEnum = someKeys.[_NewEnum]
End Property

示例

Option Explicit
Private someKeys As Dictionary
Private someCols As Collection
Public Function Add(o As Object, Key As String) As Object
    someKeys.Add Key, o
    someCols.Add o, Key
End Function
Public Property Get Count() As Long
    Count = someCols.Count
End Property
Public Property Get Item(vKey As Variant) As Object
    Set Item = someCols.Item(vKey)
End Property
Public Sub Remove(vKey As Variant)
    someKeys.Remove vKey
    someCols.Remove vKey
End Sub
Public Property Get NewEnum() As IUnknown
   Set NewEnum = someCols.[_NewEnum]
End Property
Public Property Get Keys() As Variant
    Keys = someKeys.Keys
End Property
Private Sub Class_Initialize()
    Set someKeys = New Dictionary
    Set someCols = New Collection
End Sub

这篇关于获取Collection对象上的项的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆