Retrieving data from a VB.NET arraylist of objects

拥有回忆 提交于 2019-12-22 05:05:07

问题


I am trying to retrieve the correct value from an ArrayList of objects (.NET 1.1 Framework):

I have the following defined:

Public AlList As New ArrayList

Public Class ItemInfo
    Public ItemNo As Int16
    Public ItemType As String
    Public Reports As Array
    Public PDFs As Array
End Class

The form_load event code contains:

Dim AnItemObj As New ItemInfo

Then a loop that includes:

AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)

So I should now have an ArrayList of these objects, however if I try to retrieve the data:

MsgBox(AlList(5).ItemNo)

I always get the ItemNo of the last value in the list.

What am I missing?


回答1:


Put the following code:

Dim AnItemObj As New ItemInfo

inside the loop which adds AnItemObj to the list.

When you add a reference type to a list, you are only adding the reference, not the value.

This means that if you add 10 times the same instance to a list, it will add 10 times the same reference to the list. But if afterward you still have a reference to this instance you can modify its properties and as all 10 entries in the list point to the same reference in memory, all 10 entries will be modified.




回答2:


So, you've got:

Dim AnItemObj As New ItemInfo
For ...
    AnItemObj.ItemNo = AFile.RecordId
    AnItemObj.ItemType = temp
    AlList.Add(AnItemObj)
Next

What is happening here is you're creating a single object, setting the values on it, and adding a reference to it, to your list. You're then changing your ItemInfo and addign another reference to the same item to your list

You need to construct a new object on each loop, loosely thus:

Dim AnItemObj As ItemInfo
For ...
    AnItemObj = New ItemInfo
    AnItemObj.ItemNo = AFile.RecordId
    AnItemObj.ItemType = temp
    AlList.Add(AnItemObj)
Next



回答3:


Are you creating a new instance of iteminfo for each increment of the loop?




回答4:


I can't see your full loop code but I imagine the cause is not setting AnItemObj to a New ItemInfo object. So you just end up modifying the same object and adding it the the list again (all items in the list point to the same object).

AnItemObj = New ItemInfo()
AnItemObj.ItemNo = AFile.RecordId
AnItemObj.ItemType = temp
AlList.Add(AnItemObj)


来源:https://stackoverflow.com/questions/1062320/retrieving-data-from-a-vb-net-arraylist-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!