2014-10-09 51 views
0

我所擁有的是一個對象,它包含一個對象列表,每個對象都包含另一個具有屬性的對象列表。傳遞方法與直接訪問嵌套對象

目前我使用直通方法,以便能夠在這個非常簡單的例子添加到這些嵌套的對象,如:

Public Class clsA 

Private objB As List(Of clsB) = New List(Of clsB) 

Public Sub New() 
    objB.Add(New clsB) 
End Sub 

Public Sub AddInt(ByVal BIndex As Int32, ByVal CIndex As Int32, ByVal Number As Int32) 
    objB(BIndex).AddInt(CIndex, Number) 
End Sub 

End Class 

Public Class clsB 

Private objC As List(Of clsC) = New List(Of clsC) 

Public Sub New() 
    objC.Add(New clsC) 
End Sub 

Public Sub AddInt(ByVal CIndex As Int32, ByVal Number As Int32) 
    objC(CIndex).AddInt(Number) 
End Sub 

End Class 

Public Class clsC 

Private lstNum As List(Of Int32) = New List(Of Int32) 

Public Sub AddInt(ByVal Number As Int32) 
    lstNum.Add(Number) 
End Sub 

End Class 

這似乎是正確的編碼標準會告訴我這是正確的比較:

Public Class clsD 

Public objE As List(Of clsE) = New List(Of clsE) 

Public Sub New() 
    objE.Add(New clsE) 
End Sub 

End Class 

Public Class clsE 

Public objF As List(Of clsF) = New List(Of clsF) 

Public Sub New() 
    objF.Add(New clsF) 
End Sub 

End Class 

Public Class clsF 

Public lstNum As List(Of Int32) = New List(Of Int32) 

End Class 

是否有一些情況下,哪種方法可以接受?或者傳遞設置始終是首選?

Public Class Form1 

Dim oA As clsA = New clsA 
Dim oD As clsD = New clsD 

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 

    oA.AddInt(0, 0, 3) 
    oD.objE(0).objF(0).lstNum.Add(3) 

End Sub 
End Class 

回答

1

想想如何在整個.NET Framework中完成它。該集合應分配給私人字段並通過公開的只讀屬性公開。然後

Public Class Thing 

    Private _stuff As New List(Of Thing) 

    Public ReadOnly Property Stuff() As List(Of Thing) 
     Get 
      Return _stuff 
     End Get 
    End Property 

End Class 

主叫方可以直接訪問集合調用它Add方法等,但不能指定一個全新的集合。有例子比比皆是:Control.ControlsListBox.ItemsComboBox.ItemsListView.ItemsDataSet.TablesDataSet.RelationsDataTable.RowsDatatable.Columns,等,等,等

+0

我知道我見過很多這樣的例子,但從來沒有對我的應用程序的連接。感謝您的建議,這是查看它的好方法。 – Capellan 2014-10-09 14:07:54