我已经定义了一个存储需求信息的类。它包含一个唯一的req-key。
Option Explicit
Private pKey As String
Private pName As String
Private pReqRef As New clsReqCollection
Private pReqType As RequirementType
Private pProblem As String
Public Enum RequirementType
Ziel = 0
Fachanforderung = 1
Produktanforderung = 2
Prozessanforderung = 3
Organisationsanforderung = 4
ITAnforderung = 5
Datenanforderung = 6
RandUndRahmenbedingung = 7
End Enum
''''''''''''''''''''''
' Key property
''''''''''''''''''''''
Public Property Get Key() As String
Key = pKey
End Property
Public Property Let Key(Value As String)
pKey = Value
End Property
''''''''''''''''''''''
' Name property
''''''''''''''''''''''
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(Value As String)
pName = Value
End Property
''''''''''''''''''''''
' ReqRef property
''''''''''''''''''''''
Public Property Get ReqRef() As clsReqCollection
ReqRef = pReqRef
End Property
''''''''''''''''''''''
' ReqType property
''''''''''''''''''''''
Public Property Get ReqType() As RequirementType
ReqType = pReqType
End Property
Public Property Let ReqType(Value As RequirementType)
pReqType = Value
End Property
''''''''''''''''''''''
' Problem property
''''''''''''''''''''''
Public Property Get Problem() As String
Problem = pProblem
End Property
Public Property Let Problem(Value As String)
pProblem = Value
End Property
现在我构建一个自定义集合来存储需求对象,如下所示
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "clsReqCollection"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
Private requirements As Collection
Private Sub Class_Initialize()
Set requirements = New Collection
End Sub
Private Sub Class_Terminate()
Set requirements = Nothing
End Sub
Public Function NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
Set NewEnum = requirements.[_NewEnum]
End Function
Public Sub Add(aRequirement As clsRequirement)
requirements.Add aRequirement, aRequirement.Key
End Sub
Public Sub Remove(cIndex As Variant)
requirements.Remove cIndex
End Sub
Public Property Get Item(cIndex As Variant) As clsRequirement
Attribute Item.VB_UserMemId = 0
Set Item = requirements.Item(cIndex)
End Property
Public Property Get Count() As Integer
Count = requirements.Count
End Property
Public Sub Clear()
Set requirements = New Collection
End Sub
当我使用对象存储密钥添加objekts时,我希望能够通过提供密钥来访问自定义集合:
Dim reqs As New clsReqCollection
Dim currReq As clsRequirement
Set currReq = New clsRequirement
currReq.Key = "Key"
currReq.Name = "Name"
reqs.Add currReq
Debug.Print reqs.Item("Key").Name
不知怎的,最后一行不起作用,我得到一个运行时错误'5'。知道这里出了什么问题吗?
答案 0 :(得分:0)
像这样:
Dim reqs As New clsReqCollection
Dim currReq As clsRequirement
Set currReq = New clsRequirement
currReq.Key = "Key"
currReq.Name = "Name"
reqs.Add currReq, "Key"
Debug.Print reqs.Item("Key").Name
请参阅reference:
不考虑用户定义的.Key,这只是您班级的普通成员。只有内部集合键可以用作哈希表,如获取项目的键。