我正在嘗試在C#上做一個簡單的任務,將對象放入列表中,之前我做過,但從未遇到過這個問題。經過幾次搜索,遇到了類似問題的人,以及一些解決方案,但沒有解決我的問題,這裏是代碼。列表包含重複的項目
static void GenerateRooms(int RoomsNumber)
{
int randomWidth;
int randomHeight;
Room newRoom = null;
for (int i = 0; i < RoomsNumber; i++)
{
//Create new rooms and store it on the list
randomWidth = rand.Next(_MinRoomW, _MaxRoomW + 1);
randomHeight = rand.Next(_MinRoomH, _MaxRoomH + 1);
//Room(x, y, id)
newRoom = new Room(randomWidth, randomHeight, i);
//1
_RoomsL.Insert(i, newRoom);
}
}
評論1後,我居然搜索列表中,所有的對象都沒有,從0到最後一個,但是當我退出此功能的任何其他,這樣的一個實例:
static void CheckList()
{
foreach(Room nextRoom in _RoomsL)
{
Console.WriteLine(" This room have the id: " + nextRoom.GetId());
}
}
所有對象到該列表有相同的ID,在這種情況下,ID等於在第一種方法在列表上添加的對象...
因此,它像:
GenerateRooms(RoomsNumber); << at the end of this function, the list is ok.
CheckList(); << just after exiting the last function and checking the same list, all the objects are the same.
我也試過使用list.Insert
,但沒有改變任何東西。我真的不知道該怎麼做。
Room Class。
class Room
{
//This is random.
public static Random rand = new Random();
//Room variables
public static int rWIDTH, rHEIGHT;
public static int ROOMID;
public Room(int X, int Y, int id)
{
rWIDTH = X;
rHEIGHT = Y;
ROOMID = id;
}
public int GetWidth()
{
return rWIDTH;
}
public int GetHeight()
{
return rHEIGHT;
}
public int GetId()
{
return ROOMID;
}
}
您可以請發佈您的Room.GetId()方法嗎?這會有所幫助。 – c0d3b34n
或Room類 –
爲什麼每種方法都是靜態的?看起來你在課堂上沒有無國籍的東西,所以讓一切都靜止不是一個好設計。無論如何,這不是一個代碼審查平臺;-) – Mat