VB.NET Dictionary中使用自定义类仅能获取最后一条记录的问题
问题:Dictionary存储自定义类后仅能检索到最后一条记录
我想要创建一个以产品ID为键、值为包含产品信息的自定义ProductClass类的Dictionary。看似正确存储了信息,但实际只能检索到最后一条记录,请问哪里出错了?
原代码
Public Class ProductClass Public id As Integer Public name As String Public details As String End Class Sub Test Dim i As Integer Dim singleProduct As New ProductClass Dim testDb As New Dictionary(Of Integer, ProductClass) For i = 1 To 3 singleProduct.id = i singleProduct.name = "Product " & i singleProduct.details = "blablabla" testDb.Add(singleProduct.id, singleProduct) Next i For Each dbKey As Integer In testDb.Keys Debug.Print(dbKey & " :: " & testDb(dbKey).name & vbCrLf) Next End Sub
调试输出
1 :: Product 3 2 :: Product 3 3 :: Product 3
错误原因
问题出在你只创建了一个ProductClass实例。在循环中,你反复修改同一个singleProduct对象的属性,然后将该对象的引用添加到Dictionary中。Dictionary存储的是对象的引用而非副本,因此所有键指向的都是同一个对象。循环结束后,这个对象的属性被最后一次循环的数值覆盖,导致所有条目显示的都是最后一条记录的内容。
修正方案
在每次循环内部创建新的ProductClass实例,确保每个键关联独立的对象:
Public Class ProductClass Public id As Integer Public name As String Public details As String End Class Sub Test Dim i As Integer Dim testDb As New Dictionary(Of Integer, ProductClass) For i = 1 To 3 ' 每次循环初始化新的实例 Dim singleProduct As New ProductClass singleProduct.id = i singleProduct.name = "Product " & i singleProduct.details = "blablabla" testDb.Add(singleProduct.id, singleProduct) Next i For Each dbKey As Integer In testDb.Keys Debug.Print(dbKey & " :: " & testDb(dbKey).name & vbCrLf) Next End Sub
修正后调试输出
1 :: Product 1 2 :: Product 2 3 :: Product 3
内容的提问来源于stack exchange,提问作者Karlis
相关产品推荐
相关产品推荐

