简体   繁体   English

如何在VB.NET中使用Dictionary类

[英]How to use Dictionary class in VB.NET

I am trying to create a Dictionary collection of keys, where each key would have a corresponding value of class "look". 我正在尝试创建字典的键集合,其中每个键将具有类“ look”的对应值。 The following example does not work. 以下示例不起作用。 It gives me: 它给了我:
first - circle, blue 第一圈-蓝色
second - circle, blue 第二圈-蓝色
While I need: 虽然我需要:
first - square, red 第一-正方形,红色
second - circle, blue 第二圈-蓝色
Why does it not work and how can I make it work? 为什么它不起作用?如何使它起作用?
Thank you. 谢谢。

Public Class Form1

Public Class look
    Public shape As String
    Public color As String
End Class

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myDict As New Dictionary(Of String, look)
    Dim oLook As New look
    oLook.shape = "square"
    oLook.color = "red"
    myDict.Add("first", oLook)
    oLook.shape = "circle"
    oLook.color = "blue"
    myDict.Add("second", oLook)
    For Each key In myDict.Keys
        MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
    Next
End Sub
End Class

You need a new instance of the class: 您需要一个新的类实例:

    Dim myDict As New Dictionary(Of String, look)
    Dim oLook As New look
    oLook.shape = "square"
    oLook.color = "red"
    myDict.Add("first", oLook)
    oLook = New look '<<<<<<<<<<<<
    oLook.shape = "circle"
    oLook.color = "blue"
    myDict.Add("second", oLook)
    For Each key In myDict.Keys
        MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
    Next

Try this: 尝试这个:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myDict As New Dictionary(Of String, look)
    Dim oLook As New look
    oLook.shape = "square"
    oLook.color = "red"
    myDict.Add("first", oLook)
    oLook = new look ' This will create another oLook object and point olook at it.
    oLook.shape = "circle"
    oLook.color = "blue"
    myDict.Add("second", oLook)
    For Each key In myDict.Keys
        MsgBox(key & " - " & myDict(key).shape & ", " & myDict(key).color)
    Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM