我无法映射这些类:
它们形成了一种组合关系,详见this wikipedia article。
班级订单的实例有几个托盘对象,其中包含多个 Box 对象。
这就是我现在所拥有的:
class Order
{
public Order(){}
private List<Pallet> _pallets = new List<Pallet>;
public Pallet Add_pallet()
{
Pallet new_pallet = new Pallet(this);
this._pallets.Add(new_pallet);
return new_pallet;
}
//...other properties and methods...
}
class Pallet
{
private Order _parent_order;
private List<Box> _boxes = new List<Box>;
public Pallet(Order parent_order)
{
_parent_order = parent_order;
}
public Box Add_Box()
{
Box new_box = new Box(this);
this._boxes.Add(new_box);
return new_box;
}
//...other properties and methods...
}
class Box
{
private Pallet _parent_pallet;
public Box(Pallet parent_pallet){}
//...other properties and methods...
}
所有框必须属于托盘,所有托盘必须属于订单。
如何正确实现这一点以避免这种情况:
static class Program
{
static void Main()
{
Order myOrder = new Order();
Pallet myPallet = new Pallet(myOrder);
//Now I have a Pallet that belongs to an Order,
//but the Order object is not aware of it
}
}
我应该使用嵌套类还是有些更有用的东西?
答案 0 :(得分:0)
我会这样做:
public class Order
{
private List<Pallet> _pallets = new List<Pallet>;
internal void Add_pallet(Pallet pallet)
{
if (!this._pallets.Contains(pallet))
this._pallets.Add(pallet);
}
//...other properties and methods...
}
public class Pallet
{
private Order _parent_order;
private List<Box> _boxes = new List<Box>;
public Pallet(Order parent_order)
{
if (parent_order = null)
throw ArgumentNilException("parent_order must not be null");
_parent_order = parent_order;
_parent_order.Add_pallet(this);
}
//...other properties and methods...
}
ASO。