我有关于填充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.
}
}
答案 0 :(得分:6)
您收到了错误消息,因为在您创建新的hotel
时,您尚未向其中添加任何room
。您的代码必须执行以下操作:
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 });
}
}
答案 1 :(得分:2)
您尚未向酒店添加房间:
h[i] = new hotel();
var room = new room();
room.roomName = word;
h[i].rooms.Add(room);
答案 2 :(得分:1)
使用,您需要将room
添加到hotel
h[i].rooms.Add(new room {roomName = word});
而不是
h[i].rooms[i].roomName = word;
答案 3 :(得分: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();