我有一个列表,我想提供对包含其内容的集合的只读访问权限。我怎么能这样做?
类似的东西:
public ICollection<Foo> ImmutableViewOfInventory() {
IList<Foo> inventory = new List<Foo>();
inventory.add(new Foo());
return inventory.ImmutableView();
}
此外,不可变的IEnumerable
也可以。
更新:我现在意识到列表的不可变视图实际上会更好。 (保留列表排序语义。)
这不会给我列表行为,对:
public ReadOnlyCollection<PickUp> InventoryItems()
{
return new ReadOnlyCollection<PickUp>(inventory);
}
我正在查看文档,但没有立即看到ReadOnlyList<T>
。
答案 0 :(得分:22)
如果您想要一个不可变的项目列表,可以通过调用列表中的ReadOnlyCollection方法返回AsReadOnly():
public IList<Foo> ImmutableViewOfInventory()
{
List<Foo> inventory = new List<Foo>();
inventory.Add(new Foo());
return inventory.AsReadOnly();
}
这将返回IList
的实现,该实现既强类型又不可修改。
不但是阻止更改列表中包含的任何项目(除非它们是值类型)。为此,必须克隆每个项目(如果它们本身包含其他对象,则进行深度克隆),并将其添加到从ImmutableViewOfInventory
方法返回的新只读列表中。不幸的是,你必须自己实现这一点。
答案 1 :(得分:3)
你看过ReadOnlyCollection&lt; T&gt;?
答案 2 :(得分:0)
new ReadOnlyCollection(inventory);