如果调用代码只对集合进行迭代,那么是否有任何理由将内部集合公开为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接口足够,那么它就是可以使用的接口.这是正确的推理方式还是我遗漏了什么?
谢谢/埃里克