c# - 如何正确使用 IReadOnlyDictionary?

标签 c# dictionary readonly-collection

来自 msdn :

Represents a generic read-only collection of key/value pairs.

但是请考虑以下内容:

class Test
{
    public IReadOnlyDictionary<string, string> Dictionary { get; } = new Dictionary<string, string>
    {
        { "1", "111" },
        { "2", "222" },
        { "3", "333" },
    };

    public IReadOnlyList<string> List { get; } =
        (new List<string> { "1", "2", "3" }).AsReadOnly();
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();

        var dictionary = (Dictionary<string, string>)test.Dictionary; // possible
        dictionary.Add("4", "444"); // possible
        dictionary.Remove("3"); // possible

        var list = (List<string>)test.List; // impossible
        list.Add("4"); // impossible
        list.RemoveAt(0); // impossible
    }
}

我可以轻松地将 IReadOnlyDictionary 转换为 Dictionary(任何人都可以)并更改它,而 List 有不错的 AsReadOnly 方法。

问题:如何正确使用IReadOnlyDictionary来公开确实是只读的字典?

最佳答案

.NET 4.5 引入了 ReadOnlyDictionary您可以使用的类型。它有一个接受现有字典的构造函数。

针对较低的框架版本时,使用包装器,如 Is there a read-only generic dictionary available in .NET? 中所述和 Does C# have a way of giving me an immutable Dictionary? .

请注意,使用后一个类时,集合初始化器语法将不起作用;被编译为 Add() 调用。

关于c# - 如何正确使用 IReadOnlyDictionary?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560619/

相关文章:

Python 3 - 元组超出范围错误。但我用的是字典?

c# - 为什么 ReadOnlyCollection 不允许协方差?

c# - List<T> 如何使用 ReadOnly 列表复制构造函数?

c# - 将外部 EXE 设置为 TopMost

c# - 具有 lambda 表达式的对象列表中的累积和 C#

c# - yield 是如何枚举的?

c# - 我应该使用 C# 中的哪种只读、保留顺序的集合来支持枚举?

c# - 将具体类转换为具有通用类型接口(interface)的通用接口(interface)会导致无效转换异常

python - 最Pythonic的用于从基于字典键的字典列表中选择一个条目?

python - 如何访问特定键具有特定值的字典中的所有字典