我所拥有的是一个包含对象列表的对象,每个对象都包含另一个具有属性等的对象列表。
目前我使用传递方法来添加到那些嵌套对象,就像在这个极其简化的例子中一样:
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
答案 0 :(得分: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.Controls
,ListBox.Items
,ComboBox.Items
,ListView.Items
,DataSet.Tables
,DataSet.Relations
,DataTable.Rows
,{{1等等,等等。