c# - 只读列表<字典<>>

标签 c# dictionary collections readonly-collection

如果我们有字段 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/

相关文章:

c# - 在 LINQ 中按时间跨度分组

c# - 其中 T : IEnumerable<T> method constraint

java - 按降序对对象列表进行排序

c# - 如何检查 ObservableCollection 中的重复项?

c# - 使用 SignalR 将通知从 Web 应用程序推送到桌面 Windows 窗体应用程序的可行性

c# - Entity Framework 代码优先无法正常工作

python - 从列表元组中正确赋值

python - 通过字典的字典的元组获取值

c# - 如何使用 C# 代码从 teamcity 8.1.2 下载工件

c# - 为什么我的字典包含两个键相同的条目?