說我有一個名爲Person類中,有一個姓名和年齡的屬性,並呼籲家庭,與像收入,地址屬性的另一個集合,和裏面的人的集合它。 我找不到一個關於如何實現這個概念的完整例子。 此外,由於我對集合和類都很陌生,因此我也沒有成功地使用這兩個函數來創建一個小子程序。如何定義和使用ClassA的集合的ClassB的
這是我最好的嘗試,基於有限的資源在互聯網上公佈:
' Inside the class Module Person .........................
Public pName As String
Public pAge As Integer
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(value As String)
pName = value
End Property
' Inside the class Module Family .........................
' ... Income and address Properties are supposed
' ... declared and will not be used in this trial
Private colPersons As New Collection
Function AddP(aName As String, anAge As integer)
'create a new person and add to collection
Dim P As New Person
P.Name = aName
P.Age = anAge
colPersons.Add R ' ERROR! Variable colPersons not Defined!
End Function
Property Get Count() As Long
'return the number of people
Count = colPersons.Count
End Property
Property Get Item(NameOrNumber As Variant) As Person
'return this particular person
Set Item = Person(NameOrNumber)
End Property
而現在的子程序嘗試使用上面:
Sub CreateCollectionOfPersonsInsideAFamily()
'create a new collection of people
Dim Family_A As New Family
'add 3 people to it
Family_A.AddP "Joe", 13
Family_A.AddP "Tina", 33
Family_A.AddP "Jean", 43
'list out the people
Dim i As Integer
For i = 1 To Family_A.Count
Debug.Print Family_A.Item(i).Name
Next i
End Sub
當然,這是給錯誤:變量未定義(見上面的評論)
你爲什麼需要分開類?有沒有理由人員和家庭的細節不在一個類? –
實際上,在像微軟項目這樣的程序中,我們有類似的課程和任務。兩者都有很多獨立的方法,屬性等,我不能認爲它們是一個實體:相同的資源將用於許多任務!我個人和家庭的例子就是簡化問題。 –