2012-03-26 8 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 

だから私はそれをテストし、私はfood > cheese1 > info > attributes2 > nameで、たとえば、nameを引っ張ってトリクルダウンどうやっMsgBox()を使用したい場合は?

編集:私はちょうどArrayinfoでのニーズが連想配列のための辞書をすることに気づい ので、そのエラーを無視してください、ちょうどそれがこの質問のために辞書であると仮定します。

+1

これはコードの匂いが非常に悪いです。どこでもクラスの属性(プロパティ)にアクセスするのではなく、辞書のキーと値だけにアクセスします。それはあなたの意図ですか? –

答えて

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 

はまだ、おそらくより良い方法がありますが、それは、説明のためだけにここにあります。抽出項目を助けるためにいくつかのメソッドを提供

+0

その答えは私が求めている以上のものです!ありがとう! :) – Matt

0

は役立つだろうが、あなたはそれが

food.Item( "cheese1")になります持っているように私は、構文を信じています。info.Item( "attributes2")(0)。項目( "名前")

関連する問題