2012-03-26 55 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)。項目(「名稱」)