我正在尝试创建一个Dictionary集合,其中每个键都有一个对应的class" look"。
以下示例不起作用。它给了我:
第一个 - 圆圈,蓝色
第二个 - 圆圈,蓝色
虽然我需要:
第一方,红色
第二个 - 圆圈,蓝色
为什么它不起作用,我怎样才能使它工作?
谢谢。
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
答案 0 :(得分:2)
您需要一个新的类实例:
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
答案 1 :(得分:2)
试试这个:
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