我试图在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
,但没有改变任何内容。我真的不知道该怎么做。
房间等级。
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;
}
}
答案 0 :(得分:3)
public static int ROOMID;
如果它是一个静态变量,它会持续通过该类的任何实例。所以让它变得不静止。
我建议你重新编写代码看起来像标准化的C#类:
首先将随机变量rand
移动到调用类(因此将其从Room中删除)
然后为您的房间类:
public class Room
{
//Room variables
public int Width {get;set;}
public int Height {get;set;}
public int RoomID {get;set;}
public Room(int width, int height, int id)
{
Width = width;
Height = height;
RoomID = id;
}
}
并获取如下属性:
Room room = new Room(width,height,id);
Console.WriteLine(room.Width+" is the room width");
等