如何在类中填充 list 元素
本文关键字:元素 list 填充 | 更新日期: 2023-09-27 18:32:39
我在填充list<>
元素时遇到问题。我试图为对象的第一个元素设置一个值list<>
但它不起作用。这是我的两个类:
.CLASS
class hotel
{
public List<room> rooms = new List<room>();
}
class room
{
public string roomName;
}
表格1.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.
}
}
您
收到错误是因为,虽然您创建了一个新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 });
}
}
您尚未向酒店添加客房:
h[i] = new hotel();
var room = new room();
room.roomName = word;
h[i].rooms.Add(room);
在你的类中有一个快捷方式方法可能更容易:
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();
使用,您需要将room
添加到hotel
h[i].rooms.Add(new room {roomName = word});
而不是
h[i].rooms[i].roomName = word;