开发者

Working with collections C#

If I have a aggregate object e.g. Order --> OrderLine where my Order object is identified as the aggregate root, the开发者_如何转开发refore to add OrderLine to the Order I would expect to do so through the aggregate root and by no other means e.g. Order.AddOrderLine(OrderLine line).

The Order object obviously exposes a collection of OrderLines, but how do I prevent consumers using this collection directly to add OrderLines, I assume the answer is to use a Readonly collection?? Does this stop consumers changing the state of the objects i.e. OrderLines within the collection??

Thanks


Expose your orderLines as IEnumerable < OrderLine > and implement Add/Remove methods as necessary. That way your clients can only iterate on the collection, not manipulate it w/o going thru your aggregate.


Marking a collection with the readonly keyword will just keep the collection reference from being reassigned, but not prevent modifying the contents of the collection.

You can use the List(T).AsReadOnly method to return a ReadOnlyCollection instance, though, which sounds like what you are wanting.

http://msdn.microsoft.com/en-us/library/e78dcd75.aspx


If you do not want to expose your OrderLine objects you should think of another way of passing an OrderLine to your Order, e.g. submitting only meta information in a separate class like in my example below:

/// <summary>
/// Represents an order, order lines are not accessible by other classes
/// </summary>
public class Order
{
    private readonly List<OrderLine> _orderLines = new List<OrderLine>();

    public void AddOrderLineFromProperties(OrderLineProperties properties)
    {
        _orderLines.Add(properties.CreateOrderLine());
    }
}

/// <summary>
/// Class which contains orderline information, before it is 
/// "turned into a real orderline"
/// </summary>
public class OrderLineProperties
{
    public OrderLine CreateOrderLine()
    {
        return new OrderLine();
    }
}

/// <summary>
/// the concrete order line
/// </summary>
public class OrderLine
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜