2016-09-23 5 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); 
     } 
    } 

, 사실은 목록을 검색하고, 모든 개체는 0에서 마지막에,이,하지만 때 나는 예를 들어 하나처럼, 다른이 기능을 종료 :

그리스트에
static void CheckList() 
    { 
     foreach(Room nextRoom in _RoomsL) 
     { 
      Console.WriteLine(" This room have the id: " + nextRoom.GetId()); 
     } 
    } 

모든 객체

... 동일한 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; 
    } 

} 
+7

Room.GetId() 메소드를 게시 할 수 있습니까? 이것은 도움이 될 것입니다. – c0d3b34n

+1

또는 Room 클래스 –

+1

각 메서드가 정적 인 이유는 무엇입니까? 클래스 안에 무국적자가있는 것 같지 않습니다. 따라서 정적 인 모든 것이 좋은 디자인이 아닐 수 있습니다. 어쨌든 이것은 코드 리뷰 플랫폼이 아닙니다 ;-) – Mat

답변

3
public static int ROOMID; 

, 그것은 클래스의 인스턴스를 통해 지속됩니다. 그래서 정전기가 없도록하십시오.

먼저 (룸에서 그렇게 제거)하여 확률 변수 rand에 호출 클래스를 이동 객실 클래스에 대한 다음

:

난 당신이 표준화 된 C# 클래스처럼 보이도록 코드를 재 작업 제안

이 같은
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

관련 문제