我正在尝试在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