简体   繁体   English

使用集合C#

[英]Working with collections C#

If I have a aggregate object eg Order --> OrderLine where my Order object is identified as the aggregate root, therefore to add OrderLine to the Order I would expect to do so through the aggregate root and by no other means eg Order.AddOrderLine(OrderLine line). 如果我有一个聚合对象,例如Order-> OrderLine,其中我的Order对象被标识为聚合根,那么我希望将OrderLine添加到Order中是希望通过聚合根而不是通过其他方式(例如Order.AddOrderLine( OrderLine行)。

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?? Order对象显然公开了OrderLines的集合,但是如何防止消费者直接使用此集合来添加OrderLines,我假设答案是使用Readonly集合? Does this stop consumers changing the state of the objects ie OrderLines within the collection?? 这会阻止消费者更改集合中对象(即OrderLines)的状态吗?

Thanks 谢谢

Expose your orderLines as IEnumerable < OrderLine > and implement Add/Remove methods as necessary. 将您的orderLines公开为IEnumerable <OrderLine>,并根据需要实现Add / Remove方法。 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. 用readonly关键字标记一个集合只会阻止重新分配该集合引用,但不会阻止修改该集合的内容。

You can use the List(T).AsReadOnly method to return a ReadOnlyCollection instance, though, which sounds like what you are wanting. 但是,您可以使用List(T).AsReadOnly方法返回ReadOnlyCollection实例,这听起来像您想要的。

http://msdn.microsoft.com/en-us/library/e78dcd75.aspx 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, eg submitting only meta information in a separate class like in my example below: 如果您不想公开OrderLine对象,则应考虑将OrderLine传递给Order的另一种方法,例如,仅在单独的类中提交元信息,例如下面的示例:

/// <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
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM