【发布时间】:2010-10-04 05:33:40
【问题描述】:
如果调用代码仅迭代集合,是否有任何理由将内部集合公开为 ReadOnlyCollection 而不是 IEnumerable?
class Bar
{
private ICollection<Foo> foos;
// Which one is to be preferred?
public IEnumerable<Foo> Foos { ... }
public ReadOnlyCollection<Foo> Foos { ... }
}
// Calling code:
foreach (var f in bar.Foos)
DoSomething(f);
在我看来,IEnumerable 是 ReadOnlyCollection 接口的子集,它不允许用户修改集合。因此,如果 IEnumberable 接口足够了,那么它就是可以使用的接口。这是一种正确的推理方式还是我错过了什么?
谢谢/埃里克
【问题讨论】:
-
如果您使用的是 .NET 4.5,您可能想尝试新的 read-only collection interfaces。如果您偏执,您仍然希望将返回的集合包装在
ReadOnlyCollection中,但现在您不依赖于特定的实现。
标签: c# .net collections ienumerable readonly-collection