2016-09-23 93 views
0

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

} 
+7

您可以请发布您的Room.GetId()方法吗?这会有所帮助。 – c0d3b34n

+1

或Room类 –

+1

为什么每种方法都是静态的?看起来你在课堂上没有无国籍的东西,所以让一切都静止不是一个好设计。无论如何,这不是一个代码审查平台;-) – Mat

回答

3
public static int ROOMID; 

如果它是一个静态变量,它仍然存在通过类的任何实例。所以让它变成静态的。

我建议你返工你的代码看起来像一个标准的C#类:

第一(从房间取出所有的)移动你的随机变量rand来调用类

然后为您的房间等级:

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"); 

+3

使所有变量不变为静态:-) – c0d3b34n

+2

好吧我现在只是觉得这么笨,xD,我犯了同样的错误,当我开始编程时,现在已经过了将近3年,现在又来了。 代码现在正在工作,我会实施您的建议,非常感谢。 :) (我需要一些睡眠) – JeffCarvalho

+0

没问题@JeffCarvalho,我还写了一个关于如何让你的类看起来更像标准C#代码:)的建议。 – Tyress

相关问题