C#で単純なタスクを実行しようとしていましたが、オブジェクトをリストに入れようとしましたが、これまでにこの問題を抱えていませんでした。いくつかの検索の後、似たような問題を抱えている人々といくつかの解決策がありますが、私の問題は解決していません。コメント1後リストに繰り返し項目が含まれています
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);
}
}
、私が実際にリストを検索し、すべてのオブジェクトは、0から最後まで、ありますが、私はインスタンスの1つのように、他にこの機能を終了する場合:
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;
}
}
Room.GetId()メソッドを投稿してください。これは参考になります。 – c0d3b34n
またはルームクラス –
各メソッドは静的なのはなぜですか?クラス内にステートレスなものがあるようには見えないので、静的なものはすべて良いデザインではないでしょう。とにかくこれはコードレビュープラットフォームではありません;-) – Mat