这就是我所做的。正如@jtolle 所指出的,我喜欢Rob van Gelder 的example,但我为什么要满足于制作一个永远只接受一种特定对象类型(例如People)的“自定义集合类”?正如@jtolle 指出的那样,这非常烦人。
相反,我概括了这个想法并创建了一个名为UniformCollection 的新类,它可以包含任何数据类型——只要UniformCollection 的任何给定实例中的所有项目都属于同一类型。
我添加了一个私有 Variant,它是UniformCollection 的给定实例可以包含的数据类型的占位符。
Private mvarPrototype As Variant
在创建UniformCollection 的实例之后并在使用它之前,必须通过指定它将包含哪种数据类型来对其进行初始化。
Public Sub Initialize(Prototype As Variant)
If VarType(Prototype) = vbEmpty Or VarType(Prototype) = vbNull Then
Err.Raise Number:=ERR__CANT_INITIALIZE, _
Source:=TypeName(Me), _
Description:=ErrorDescription(ERR__CANT_INITIALIZE) & _
TypeName(Prototype)
End If
' Clear anything already in collection.
Set mUniformCollection = New Collection
If VarType(Prototype) = vbObject Or VarType(Prototype) = vbDataObject Then
' It's an object. Need Set.
Set mvarPrototype = Prototype
Else
' It's not an object.
mvarPrototype = Prototype
End If
' Collection will now accept only items of same type as Prototype.
End Sub
然后,Add 方法将只接受与 Prototype 具有相同类型的新项目(无论是对象还是原始变量...尚未使用 UDT 进行测试)。
Public Sub Add(NewItem As Variant)
If VarType(mvarPrototype) = vbEmpty Then
Err.Raise Number:=ERR__NOT_INITIALIZED, _
Source:=TypeName(Me), _
Description:=ErrorDescription(ERR__NOT_INITIALIZED)
ElseIf Not TypeName(NewItem) = TypeName(mvarPrototype) Then
Err.Raise Number:=ERR__INVALID_TYPE, _
Source:=TypeName(Me), _
Description:=ErrorDescription(ERR__INVALID_TYPE) & _
TypeName(mvarPrototype) & "."
Else
' Object is of correct type. Accept it.
' Do nothing.
End If
mUniformCollection.Add NewItem
End Sub
其余部分与示例中的几乎相同(加上一些错误处理)。太糟糕了 RvG 没有一路走好!更糟糕的是,微软没有将这种东西作为内置功能包含在内......