只读列表列表c#
发布时间:2020-12-15 23:31:27 所属栏目:百科 来源:网络整理
导读:一般而言,我正在制作的程序涉及存储可以分类的少量条目(在任何给定时间可能小于30).我希望允许看到这些条目,但不要使用它们从类外部进行更改.我创建了一个名为Entry的类,可以修改它,另一个名为ReadOnlyEntry,它是Entry对象的包装器.组织这些Entry对象的最简
一般而言,我正在制作的程序涉及存储可以分类的少量条目(在任何给定时间可能小于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: 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); } 解决方法
.NET集合应该支持
covariance,但它们自己不支持它(相反,某些接口支持协方差
https://msdn.microsoft.com/ru-ru/library/dd233059.aspx).协方差表示List< Conctrete>表现得像List< Base>的子类.如果Concrete是Base的子类.您可以使用接口协变或只使用这样的转换:
using System.Collections.Generic; namespace MyApp { interface IEntry { } class Entry : IEntry { } class Program { private List<List<Entry>> _matrix = null; public List<List<IEntry>> MatrixWithROElements { get { return _matrix.ConvertAll(row => row.ConvertAll(item => item as IEntry)); } } public IReadOnlyList<List<IEntry>> MatrixWithRONumberOfRows { get { return _matrix.ConvertAll(row => row.ConvertAll(item => item as IEntry)); } } public List<IReadOnlyList<IEntry>> MatrixWithRONumberOfColumns { get { return _matrix.ConvertAll(row => row.ConvertAll(item => item as IEntry) as IReadOnlyList<IEntry>); } } public IReadOnlyList<IReadOnlyList<IEntry>> MatrixWithRONumberOfRowsAndColumns { get { return _matrix.ConvertAll(row => row.ConvertAll(item => item as IEntry)); } } public void Main(string[] args) { } } } 感谢Matthew Watson指出我以前的答案版本中的错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |