实体集合的 IList 与 IEnumerable

发布于 2024-07-11 15:56:12 字数 81 浏览 7 评论 0原文

当我的域中存在包含事物列表的实体时,它们是否应该公开为 IList 或 IEnumerable? 例如,Order 有一堆 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

多孤肩上扛 2024-07-18 15:56:12

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

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

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

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.

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>.

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.

爺獨霸怡葒院 2024-07-18 15:56:12

大多数时候,我最终会使用 IList 而不是 IEnumerable,因为 IEnumerable 没有 Count 方法,并且您无法通过索引访问集合(尽管如果您使用 LINQ,则可以使用扩展方法解决此问题)。

Most of the time I end up going with IList over IEnumerable because IEnumerable doesn't have the Count method and you can't access the collection through an index (although if you are using LINQ you can get around this with extension methods).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文