2011-09-30 65 views
0

我的工作是基於地圖方格的一個小遊戲。我有一個類(clsGrid),它爲每個網格廣場存儲一些屬性。網格方形對象被組織成一個列表(clsGrid)。
循環和流讀取器正在成功讀取文本文件中的屬性,將屬性放入網格對象中,並將網格對象添加到我的網格列表中。當從網格列表中檢索一個網格時,我收到了不尋常的結果。不管我給列表中的索引,我似乎總是得到列表中的最後索引網格。調試器似乎表明,正確的數字都被讀入流讀取器,它們被添加到gridHolder。然而,在最後的消息框會一直顯示我的最後grid.id,無論我給它的索引。VB.net列表不返回索引對象

我一直在研究這個問題,這可能很愚蠢。先謝謝您的幫助。

'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 

回答

4

在GenerateMap中,您的Do Until循環每次都將相同的clsGrid實例(gridHolder)的引用添加到列表中。由於所有列表項目都引用相同的實例,因此無論索引爲I,您的消息框都會顯示相同的結果。

您需要每次通過循環創建一個新的clsGrid實例。一種方法是在循環中添加「gridHolder = New clsGrid」行作爲第一行。然後,您也可以從現有的Dim語句中刪除單詞「New」。