【发布时间】:2018-06-14 11:26:44
【问题描述】:
考虑到我想要封装它们,为我的属性使用接口是不好的做法吗?
public class Order
{
private readonly ICollection<OrderItem> _orderItems;
public IReadOnlyCollection OrderItems => _orderItems; // not possible without ToList
}
没有简单的方法来公开它,因为如果不首先使用ToList,就无法从ICollection 转换为IReadOnlyCollection 或IEnumerable,这涉及复制整个集合。
我应该将其定义为:
private readonly Collection<OrderItem> _orderItems;
或
private readonly HashSet<OrderItem> _orderItems;
或
private readonly List<OrderItem> _orderItems;
改为?
【问题讨论】:
-
始终使用尽可能小的分母。即,对于方法或构造函数中的参数,请使用
IEnmuerable<T>,除非您需要更专业的接口,即.Count或需要Add/Remove方法等。作为返回时间,最低常用值取决于您的意图。你希望人们改变结果吗?使用IList<T>或ICollection<T>不想让用户操作它?IEnumerable<T>并且它可能是可迭代的(即不立即执行)。或者返回T[],如果它应该更明确地表明它是一个数组而不是任何通用的可枚举/迭代器 -
@Tseng 是的,这里的问题更多是关于在私有字段中使用
ICollection,以便以后将其公开为IReadOnlyCollection。除此之外,我通常按照你说的去做。