如果我们有字段 List<Dictionary<>>
, 如何将其公开为只读属性?
举个例子:
public class Test
{
private List<Dictionary<string, object>> _list;
}
我可以这样曝光
public ReadOnlyCollection<Dictionary<string, object>> List
{
get { return _list.AsReadOnly(); }
}
但仍然可以更改目录:
var test = new Test();
test.List[0]["a"] = 3; // possible
test.List[0].Add("e", 33); // possible
这里尝试让它只读
public ReadOnlyCollection<ReadOnlyDictionary<string, object>> List
{
get
{
return _list.Select(item =>
new ReadOnlyDictionary<string, object>(item)).ToList().AsReadOnly();
}
}
我认为这种方法的问题很明显:它是新词典的新列表。
我想要的是类似于 List<>.AsReadOnly() 的东西, 让属性充当 _list
的包装器.
最佳答案
如果您不能创建一个新的 Dictionary
对象列表,我建议您直接从您的类中公开您需要的项目:
public IReadOnlyDictionary<string, object> this[int i]
{
get { return this._list[i]; }
}
//OR
public IReadOnlyDictionary<string, object> GetListItem(int i)
{
return _list[i];
}
public int ListCount
{
get { return this._list.Count; }
}
然后像这样使用它:
var test = new Test();
var dictionary = test[0];
//OR
dictionary = test.GetListItem(0);
int count = test.ListCount;
关于c# - 只读列表<字典<>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250636/