结合使用数组和对象初始化语法,您可以在一个语句中完成所有操作,这完全适合实例化 POCO。
var oHotel = new Hotel
{
Id = 100
room =
{
new Hotel.Room { RoomId = 1, RoomTypeid = 1, Name = "Name" }
}
};
如果想用多个房间初始化您的酒店,
var oHotel = new Hotel
{
Id = 100
room =
{
new Hotel.Room { RoomId = 1, RoomTypeid = 1, Name = "A" },
new Hotel.Room { RoomId = 2, RoomTypeid = 1, Name = "B" },
new Hotel.Room { RoomId = 3, RoomTypeid = 2, Name = "C" },
new Hotel.Room { RoomId = 4, RoomTypeid = 2, Name = "D" }
}
};
顺便说一句,你的
public Room[] room { get; set; }
属性,可能应该称为Rooms
.
如果您不想使用 POCO,就像您在问题中显示的那样,我会像这样重写您的课程,使其不可变,
public class Hotel
{
private readonly int id;
private readonly IList<Room> rooms;
public Hotel(int id; IEnumerable<Room> rooms)
{
this.id = id;
this.rooms = rooms.ToList();
}
public int Id
{
get { return this.id; }
}
public IEnumerable<Room> Rooms
{
get { return this.rooms; }
}
public class Room
{
private readonly int id;
private readonly RoomType type;
private readonly string name;
public Room(int id, RoomType type, string name)
{
}
public int Id
{
get { return this.id; }
}
public RoomType Type
{
get { return this.type; }
}
public string Name
{
get { return this.name; }
}
}
public enum RoomType
{
// Valid Room Types Here,
// ...
}
}
然后我会像这样实例化它,
var oHotel = new Hotel(
100,
{
new Hotel.Room(1, Hotel.RoomType..., "A"),
new Hotel.Room(2, Hotel.RoomType..., "B"),
new Hotel.Room(3, Hotel.RoomType..., "C"),
new Hotel.Room(4, Hotel.RoomType..., "D")
});
仍然在一个单一的声明中,但更紧凑。结果对象将是不可变的,这有许多超出问题范围的好处。