2012-03-26 54 views
1

我不确定在字典声明中访问类的属性所需的语法。VB.NET访问字典中的类变量

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()我怎么涓滴在food > cheese1 > info > attributes2 > name拉,说,name

编辑: 我刚刚意识到Arrayinfo需要是词典的关联数组,所以请忽略错误,只是假设它是一个词典这个问题的缘故。

+1

这有一些非常糟糕的代码气味。你不会在任何地方访问类属性(属性),只是字典键和值。这是你的意图吗? – 2012-03-26 15:19:06

回答

2

好,这里是如何到达那里(考虑您的Array兼顾评论):

Dim name As String = food("cheese1").info("attributes2")("name") 

如果你离开了内部字典作为<String, Array>那么你就必须这样,这将返回零字典的“名”值:

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 

可能有更好的方法还没有,但它只是来作说明。

+0

那么这个答案比我能要求的要多!谢谢! :) – Matt 2012-03-26 16:00:33

0

提供了一些方法来帮助提取项目会有所帮助,但我相信语法,你有这将是

food.Item( “cheese1”)。info.Item( “attributes2”)(0)。项目(“名称”)