一般来说,我正在制作的程序涉及存储少量可以分类的条目(在任何给定时间可能少于 30 个)。我希望允许看到这些条目,但不要在课堂外使用它们进行更改。我创建了一个可以修改的名为 Entry 的类和另一个名为 ReadOnlyEntry 的类,它是一个 Entry 对象的包装器。组织这些 Entry 对象的最简单方法似乎是创建一个List<List<Entry>>
,其中每个List<Entry>
都是一个类别。但随后以只读方式公开这些数据变得混乱和复杂。我意识到我必须拥有以下每种类型的一个对象:
List<List<Entry>> data;
List<List<ReadOnlyEntry>> // Where each ReadOnlyEntry is a wrapper for the Entry in the same list and at the same index as its Entry object.
List<IReadOnlyCollection<ReadOnlyEntry>> // Where each IReadOnlyCollection is a wrapper for the List<ReadOnlyEntry> at the same index in data.
IReadOnlyCollection<IReadOnlyCollection<ReadOnlyList>> readOnlyList // Which is a wrapper for the first item I listed.
列表中的最后一项将公开。第一个让我更改条目,第二个让我添加或删除条目,第三个让我添加或删除类别。每当数据发生变化时,我都必须保持这些包装器的准确性。这对我来说似乎很复杂,所以我想知道是否有更好的方法来处理这个问题。
编辑 1:澄清一下,我知道如何使用 List.asReadOnly(),我上面建议做的事情将解决我的问题。我只是有兴趣听到更好的解决方案。让我给你一些代码。
class Database
{
// Everything I described above takes place here.
// The data will be readable by this property:
public IReadOnlyCollection<IReadOnlyCollection<ReadOnlyList>> Data
{
get
{
return readOnlyList;
}
}
// These methods will be used to modify the data.
public void AddEntry(stuff);
public void DeleteEntry(index);
public void MoveEntry(to another category);
public void AddCategory(stuff);
public void DeleteCategory(index);
}