我正在开发一款基于网格方块地图的小游戏。我有一个类(clsGrid),为每个网格方块存储一些属性。网格方形对象被组织成一个列表(clsGrid) 循环和流阅读器成功从文本文件中读取属性,将属性放入网格对象,并将网格对象添加到我的网格列表中。从网格列表中检索网格时,我得到了不寻常的结果。无论我给出列表的索引,我似乎总是得到列表中的最后一个索引网格。调试器似乎建议将正确的数字读入流读取器并将它们添加到gridHolder中。但是,最后的消息框将始终显示最后的grid.id,无论我给它的索引。
我一直在研究这个问题,这可能是个愚蠢的事情。在此先感谢您的帮助。
'A subroutine that generates a map (list of grids)
Sub GenerateMap()
Dim reader As StreamReader = File.OpenText("map1.txt")
Dim gridHolder As New clsGrid
'The streamreader peeks at the map file. If there's nothing in it, a warning is displayed.
If reader.Peek = CInt(reader.EndOfStream) Then
MessageBox.Show("The map file is corrupted or missing data.")
reader.Close()
Else
'If the map file has information, X and Y counts are read
intXCount = CInt(reader.ReadLine)
intYCount = CInt(reader.ReadLine)
'Reads in grid properties until the end of the file
Do Until reader.Peek = CInt(reader.EndOfStream)
gridHolder.TerrainType = CInt(reader.ReadLine)
gridHolder.MovementCost = CInt(reader.ReadLine)
gridHolder.DefensiveBonus = CInt(reader.ReadLine)
gridHolder.ID = listMap.Count
listMap.Add(gridHolder)
Loop
reader.Close()
End If
End Sub
'This function returns a Grid object given an X and Y coordinate
Function lookupGrid(ByVal intX As Integer, ByVal intY As Integer) As clsGrid
Dim I As Integer
Dim gridHolder As New clsGrid
'This formula finds the index number of the grid based on its x and y position
I = ((intX * intYCount) + intY)
gridHolder = listMap.Item(I)
MessageBox.Show(gridHolder.ID.ToString)
Return gridHolder
End Function
答案 0 :(得分:4)
在GenerateMap中,Do Until循环每次都会向列表添加对同一个clsGrid实例(gridHolder)的引用。由于您的所有列表项都引用了同一个实例,因此无论索引I如何,您的消息框都会显示相同的结果。
每次循环时都需要创建clsGrid的新实例。一种方法是将“gridHolder = New clsGrid”行添加为循环中的第一行。然后,您还可以从现有的Dim语句中删除“New”一词。