0

我对填充list<>元素有疑问。我试图为list<>对象的第一个元素设置一个值,但它不起作用。这是我的两门课:

班级

        class hotel
        {
            public List<room> rooms = new List<room>();
        }
        class room
        {
            public string roomName;
        }

Form1.cs

private void Form1_Load(object sender, EventArgs e)
        {
            string word = "example";
            hotel[] h = new hotel[3];
            for (int i = 0; i < h.Length; i++)
            {

                h[i] = new hotel();
                h[i].rooms[i].roomName = word;//It gives "Index out of range exception" error. 
            }
        }
4

4 回答 4

6

您收到错误是因为,当您创建了一个新的 s 时hotel,您还没有向room其中添加任何 s 。您的代码必须执行以下操作:

for (int i = 0; i < h.Length; i++)
{
    h[i] = new hotel();
    h[i].rooms.Add(new room { roomName = word });
}

如果要添加多个房间,则需要Add多次调用或在内部循环中这样做:

for (int i = 0; i < h.Length; i++)
{
    h[i] = new hotel();
    // Add 10 rooms
    for (int a = 0; a < 10; a++)
    {
        h[i].rooms.Add(new room { roomName = word });
    }
}
于 2013-09-23T15:49:22.907 回答
2

您还没有向酒店添加房间:

h[i] = new hotel();
var room = new room();
room.roomName = word;
h[i].rooms.Add(room); 
于 2013-09-23T15:49:59.900 回答
1

在您的课程中使用快捷方法可能更容易:

public class Hotel
{
    public Hotel()
    {
        Rooms = new List<Room>();
    }

    public List<Room> Rooms { get; private set; }
    public string Name { get; private set; }

    public Hotel WithName(string name)
    {
        Name = name;
        return this;
    }

    public Hotel AddRoom(string name)
    {
        Rooms.Add(new Room { Name = name });
        return this;
    }
}

public class Room
{
    public string Name { get; set; }
}

返回Hotel对象本身将允许在同一对象上链接方法以使操作流畅地读取。

演示:

var hotels = new List<Hotel>();

var hiltonHotel = new Hotel()
                      .WithName("Hilton")
                      .AddRoom("104")
                      .AddRoom("105");

hotels.Add(hiltonHotel);

演示 2:

var hotelNames = new List<string> { "Hilton", "Sheraton", "Atlanta" };

var hotels = new List<Hotel>();

foreach(var hotelName in hotelNames)
{
    var hotel = new Hotel()
                    .WithName(hotelName);
    hotels.Add(hotel);
}

使用 LINQ 的演示 2:

var hotelNames = new List<string> { "Hilton", "Sheraton", "Atlanta" };
var hotels = hotelNames.Select(h => new Hotel().WithName(h)).ToList();
于 2013-09-23T16:01:21.477 回答
1

使用,需要添加roomhotel

h[i].rooms.Add(new room {roomName = word});

代替

h[i].rooms[i].roomName = word;
于 2013-09-23T15:49:57.910 回答