2016-09-23 94 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

相關問題