我不确定在Dictionary声明中访问类的属性所需的语法。
Public food As New Dictionary(Of String, cheese) From
{
{"cheese1", New cheese},
{"cheese2", New cheese},
{"cheese3", New cheese}
}
Public Class cheese
Public info As New Dictionary(Of String, Array) From
{
{"attributes1",
{New Dictionary(Of String, String) From
{
{"name", "test"},
{"taste", vbNullString},
{"color", vbNullString}
}
}
},
{"attributes2",
{New Dictionary(Of String, String) From
{
{"name", "test"},
{"taste", vbNullString},
{"color", vbNullString}
}
}
}
}
End Class
因此,如果我想对其进行测试并使用MsgBox()
,我该如何在name
中逐步提取food > cheese1 > info > attributes2 > name
?
编辑:
我刚刚意识到Array
中的info
需要是一个关联数组的字典,所以请忽略该错误,并假设它是一个字典来解决这个问题。
答案 0 :(得分:2)
嗯,这是如何到达那里(考虑你的Array
评论):
Dim name As String = food("cheese1").info("attributes2")("name")
如果你把那个内部字典留作<String, Array>
那么你就会有这个,这会返回第0个字典的“名字”值:
Dim name As String = food("cheese1").info("attributes2")(0)("name")
但正如我在评论中暗示的那样,设计真的很糟糕。以下是重做此方法的一种方法:
Dim food As New Food()
food.CheeseAttributes.Add(New Cheese("Cheddar", "Awesome", "Yellow"))
food.CheeseAttributes.Add(New Cheese("Pepperjack", "Spicy", "White"))
这可以通过将您的类重构为:
来实现Public Class Food
Private _cheeseAttributes As IList(Of Cheese)
Public Sub New()
End Sub
Public ReadOnly Property CheeseAttributes() As IList(Of Cheese)
Get
If _cheeseAttributes Is Nothing Then
_cheeseAttributes = new List(Of Cheese)()
End If
Return _cheeseAttributes
End Get
End Property
End Class
Public Class Cheese
Private _name As String
Private _taste As String
Private _color As String
Public Sub New (ByVal name As String, ByVal taste As String, ByVal color As String)
Me.Name = name
Me.Taste = taste
Me.Color = color
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Taste() As String
Get
Return _taste
End Get
Set(ByVal value As String)
_taste = value
End Set
End Property
Public Property Color() As String
Get
Return _color
End Get
Set(ByVal value As String)
_color = value
End Set
End Property
End Class
可能还有更好的方法,但这只是为了说明。
答案 1 :(得分:0)
提供一些方法来帮助提取项目会有所帮助,但我相信你所拥有的语法将是
food.Item(“cheese1”)。info.Item(“attributes2”)(0).Item(“name”)