2016-08-08 6 views
0

ich diese Hierarchie von Klassen haben, die definiert werden alsKlasse Passing Objekt von Eigentum get 'in einer übergeordneten Klasse wirkt sich nicht auf die verschachtelte Klassenobjekt

cQuestion folgt:

Private pText As String 

Private Sub Class_Initialize() 
pText = "" 
End Sub 

Property Let Text(T As String) 
    pText = T 
End Property 

Property Get Text() As String 
    Text = pText 
End Property 

cQuestionList:

Private pQList() As New cQuestion 
Private pListLen As Integer 

Private Sub Class_Initialize() 
    pListLen = 0 
End Sub 

Public Sub AddEnd(Q As String) 
    pListLen = pListLen + 1 
    ReDim Preserve pQList(1 To pListLen) 
    pQList(pListLen).Text = Q 
End Sub 

Public Function Format() As String 
    Dim i As Integer 
    If pListLen = 0 Then 
     FormatList = "There are no questions in this category" + vbNewLine 
    Else 
     FormatList = "Questions:" + vbNewLine 
     For i = 1 To pListLen 
      FormatList = FormatList + "• " + pQList(i).Text + vbNewLine 
     Next i 
    End If 
End Function 

cCategory:

Private pName As String 
Private pQList As New cQuestionList 

Private Sub Class_Initialize() 
    pName = "" 
End Sub 

Property Get QuestionList() As cQuestionList 
    Set QuestionList = pQList 
End Property 

Property Let Name(N As String) 
    pName = N 
End Property 

Property Get Name() As String 
    Name = pName 
End Property 

Wenn ich versuche, Category.QuestionList.AddEnd "Question Here", aufzurufen, werden keine Fehler ausgegeben. Aber wenn ich anschließend MsgBox Category.QuestionList.Format anrufe bekomme ich eine leere Nachricht. Ich bin nicht sicher, wie dies endet, da Format immer Text zurückgeben sollte. Was mache ich hier falsch? Ich habe mir andere Beispiele für das Übergeben von Klassenobjekten durch let und get in einer Elternklasse angesehen und kann nicht sehen, wie das, was ich tue, anders ist. Irgendwelche Vorschläge?

Beispielcode:

Dim C as New cCategory 
C.QuestionList.AddEnd "A Question" 
C.QuestionList.AddEnd "Another Question" 
MsgBox C.QuestionList.Format 

Antwort

2

Put Option Explicit an der Spitze jedes Moduls und Sie sehen das Problem sofort:

Public Function Format() As String 
    Dim i As Integer 
    If pListLen = 0 Then 
     FormatList = "There are no questions in this category" + vbNewLine 
      '^^^^ Variable not defined. 
    Else 
     FormatList = "Questions:" + vbNewLine 
     For i = 1 To pListLen 
      FormatList = FormatList + "• " + pQList(i).Text + vbNewLine 
     Next i 
    End If 
End Function 

Sie müssen entweder Public Function Format() As String-Public Function FormatList() As String ändern oder die FormatList ändern Zuordnungen zu Format.

Ich würde persönlich mit der FormatList Benennung gehen, um Kollisionen mit der Format Funktion zu vermeiden.

Verwandte Themen