我有以下课程;
public class Hotel
{
public int Id { get; set; }
public Room[] room { get; set; }
public class Room
{
public int RoomId { get; set; }
public int RoomTypeId { get; set; }
public string Name { get; set; }
}
}
我可以创建类的实例,如下所示,为数据分配
Hotel oHotel = null;
oHotel = new Hotel ();
oHotel.Id = 100;
但是如何为Room类创建一个子实例,我需要为Hotel类添加相关数据?
答案 0 :(得分:3)
通过给房间的建设者提供回酒店的参考。但是酒店并不了解房间,所以也为此添加一个方法:
public class Hotel
{
public int Id { get; set; }
public List<Room> Rooms { get; set; }
public void AddRoom(Room room)
{
Rooms.Add(room);
}
}
public class Room
{
public Hotel Hotel { get; private set; }
public int RoomId { get; set; }
public int RoomTypeId { get; set; }
public string Name { get; set; }
public Room(Hotel hotel)
{
this.Hotel = hotel;
}
}
然后你可以打电话:
var hotel = new Hotel();
var room = new Room(hotel);
hotel.AddRoom(room);
答案 1 :(得分:0)
public class Hotel
{
public int Id { get; set; }
public Room[] Rooms { get; set; }
public void AddRoom(int id, int typeID, string name)
{
Room room = new Room(id, typeID, name);
this.Rooms.Add(room);
}
public class Room
{
public int RoomId { get; set; }
public int RoomTypeId { get; set; }
public string Name { get; set; }
public Room(int id, int typeID, string name)
{
RoomID = id;
RoomTypeId = typeID;
Name = name;
}
}
}
客户代码:
Hotel oHotel = null;
oHotel = new Hotel ();
oHotel.Id = 100;
oHotel.AddRoom(1, 1, "Name1");
答案 2 :(得分:0)
结合使用数组和对象初始化程序语法,您可以在一个语句中完成所有操作,这完全适用于实例化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")
});
仍然在一个声明中,但更紧凑。结果对象将是不可变的,这有许多超出问题范围的好处。