实体上的集合的IList与IEnumerable [英] IList vs IEnumerable for Collections on Entities

查看:190
本文介绍了实体上的集合的IList与IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在我的域中有实体列表的事物,它们应该暴露为ILists或IEnumerables?例如。订单有一堆OrderLines。

When I have entities in my domain with lists of things, should they be exposed as ILists or IEnumerables? E.g. Order has a bunch of OrderLines.

推荐答案

IEnumerable< T> 代表一系列项目(例如使用foreach),而 IList< T> 是可以添加或删除的集合。

IEnumerable<T> represents a series of items that you can iterate over (using foreach, for example), whereas IList<T> is a collection that you can add to or remove from.

通常,您可以通过添加或删除OrderLines来修改订单,因此您可能希望Order.Lines为 IList< OrderLine>

Typically you'll want to be able to modify an Order by adding or removing OrderLines to it, so you probably want Order.Lines to be an IList<OrderLine>.

说到这里,你应该做一些框架设计决策。例如,是否可以将同一个OrderLine实例添加到两个不同的订单?可能不会。因此,假设您希望能够验证OrderLine是否应该添加到订单中,您可能希望将Lines属性仅表示为 IEnumerable ,并提供可处理该验证的Add(OrderLine)和Remove(OrderLine)方法。

Having said that, there are some framework design decisions you should make. For example, should it be possible to add the same instance of OrderLine to two different orders? Probably not. So given that you'll want to be able to validate whether an OrderLine should be added to the order, you may indeed want to surface the Lines property as only an IEnumerable<OrderLine>, and provide Add(OrderLine) and Remove(OrderLine) methods which can handle that validation.

这篇关于实体上的集合的IList与IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆