列表包含重复项目
本文关键字:项目 包含重 列表 | 更新日期: 2023-09-27 18:08:20
我试图在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;
}
}
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");
等等。