【发布时间】:2016-03-08 19:07:03
【问题描述】:
昨天我问了一个关于深度克隆列表的问题,我得到了一个很好的答案,你可以阅读here。
我遇到的问题是答案使用ImmutableList,我对此没有任何问题,只是如果我想使用 ReadOnlyCollection 并确保返回我收藏的副本并且类中的那个不能被修改。
我只是想知道以下是否正确。
private ReadOnlyCollection<Author> listofAuthors;
private List<Author> copyofAuthors;
public Book(ICollection<Author> authors)
{
copyofAuthors = new List<Author>(authors);
listofAuthors = new ReadOnlyCollection<Author>(new List<Author>(copyofAuthors));
}
public ICollection<Author> Authors
{
get
{
return new ReadOnlyCollection<Author>(new List<Author>(copyofAuthors));
}
}
根据MSDN documentation ReadOnlyCollection 只是一个底层可变集合的包装器。因此,如果对基础集合进行任何更改,它将反映在 ReadOnlyCollection 中。上面的代码 getter 返回一个新的 List 作为只读集合。
问题一:
鉴于上述代码,任何其他调用它的代码都将获得 私有 ReadOnly(new List()) 的副本,对吗?用户所做的任何更改都不会反映在 Book 类中的 ReadOnlyCollection 中,对吧?
问题 2:
我知道ImmutableList 更理想,但是如果我需要使用ReadOnlyCollection<Authors>,我在构造函数/获取器中所做的是否正确?还是可以以另一种/更好的方式实现?
【问题讨论】: