这将是:
Dim name1 As String = people(0)(0)
但是,这种结构非常混乱。您必须记住每个数组中每个索引处的事物类型,并且无法可靠地将名称与描述相关联。
最好用和属性构建一个Person
类,然后构建一个新对象列表,即使它们的某些属性是(null)。使用锯齿状数组不是很容易维护,甚至您上面的简单示例也难以接受。Name
Description
Person
Nothing
以下是我将如何处理这个问题(有一些评论用于解释)。它比您的示例代码更多,但更易于维护
Public Class Person
' Private backing fields
Private _name As String
Private _description As String
' Default constructor
Public Sub New()
End Sub
' Overloaded constructor that takes a name and optionally a description
Public Sub New(ByVal name As String, _
Optional ByVal description As String = Nothing)
Me.Name = name
Me.Description = description
End Sub
' A property (getter & setter) for Name
Public Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
' A property (getter & setter) for Description
Public Property Description As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
End Class
并创建一个新列表:
Dim people As New List(Of Person)
people.Add(new Person("Name1", "Description1"))
people.Add(new Person("Name2")) ' Description is optional
people.Add(new Person("Name3", "Description2"))
然后,您可以使用List(Of T)
该类提供的各种方法来查找列表中的操作项,而无需知道索引。
编辑:如果您想要一个人的多个描述,您的代码可能如下所示:
Public Class Person
' Private backing fields
Private _name As String
Private ReadOnly _descriptions As List(Of String) = New List(Of String)
' Default constructor
Public Sub New()
End Sub
' Overloaded constructor that takes a name and optionally a description
Public Sub New(ByVal name As String, _
Optional ByVal descriptions As IEnumerable(Of String) = Nothing)
Me.Name = name
If Not descriptions Is Nothing Then
Me.Descriptions.AddRange(descriptions)
End If
End Sub
' A property (getter & setter) for Name
Public Property Name As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
' A property (getter) for Descriptions
Public ReadOnly Property Descriptions As List(Of String)
Get
Return _descriptions
End Get
End Property
End Class
并创建一个新列表:
Dim people As New List(Of Person)
' Because the constructor takes any `IEnumerable`, you have options
' as to how you add descriptions
people.Add(new Person("Name1", New String() { "Desc1", "Desc2" }))
' or
Dim person1 As New Person("Name1")
person1.Descriptions.Add("Desc1")
person1.Descriptions.Add("Desc2")
people.Add(person1)
还有其他几种方法可以做到这一点,但这两种方法很简单。