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

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

问题描述

当我的域中有包含事物列表的实体时,它们应该作为 ILists 还是 IEnumerables 公开?例如.订单有一堆订单行.

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 表示您可以迭代的一系列项目(例如,使用 foreach),而 IList 是一个可以添加或删除的集合来自.

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.

通常,您希望能够通过添加或删除 OrderLine 来修改 Order,因此您可能希望 Order.Lines 成为 IList.

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天全站免登陆