问题描述
环境是我推入 Collection 的成员是无名的,无法识别的(为了避免糟糕的抽象,请不要惊慌:成员实际上是其他 Collection 实例).为了能够进行快速搜索,我正在为每个新成员创建一个有意义的哈希名称,并将其作为 Key 字符串提供给最顶层"集合的 Add 方法.
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.
当我有一把钥匙可以用来搜索时,一切都变得花花公子......问题是我想迭代集合的成员并获取添加时提供的密钥(生成的哈希,不幸的是无法反向哈希).
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 对象上项目的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!