Is there anything built into the core C# libraries that can give me an immutable Dictionary?

大约Java's个字:

Collections.unmodifiableMap(myMap);

我只是想澄清一下,我不是想阻止键/值本身被改变,只是想阻止字典的 struct .如果IDictionary的任何一个mutator方法被调用(Add, Remove, Clear),我希望它能够快速而响亮地失败.

推荐答案

没有,但是包装器非常简单:

public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
    IDictionary<TKey, TValue> _dict;

    public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict)
    {
        _dict = backingDict;
    }

    public void Add(TKey key, TValue value)
    {
        throw new InvalidOperationException();
    }

    public bool ContainsKey(TKey key)
    {
        return _dict.ContainsKey(key);
    }

    public ICollection<TKey> Keys
    {
        get { return _dict.Keys; }
    }

    public bool Remove(TKey key)
    {
        throw new InvalidOperationException();
    }

    public bool TryGetValue(TKey key, out TValue value)
    {
        return _dict.TryGetValue(key, out value);
    }

    public ICollection<TValue> Values
    {
        get { return _dict.Values; }
    }

    public TValue this[TKey key]
    {
        get { return _dict[key]; }
        set { throw new InvalidOperationException(); }
    }

    public void Add(KeyValuePair<TKey, TValue> item)
    {
        throw new InvalidOperationException();
    }

    public void Clear()
    {
        throw new InvalidOperationException();
    }

    public bool Contains(KeyValuePair<TKey, TValue> item)
    {
        return _dict.Contains(item);
    }

    public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
    {
        _dict.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return _dict.Count; }
    }

    public bool IsReadOnly
    {
        get { return true; }
    }

    public bool Remove(KeyValuePair<TKey, TValue> item)
    {
        throw new InvalidOperationException();
    }

    public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
    {
        return _dict.GetEnumerator();
    }

    System.Collections.IEnumerator 
           System.Collections.IEnumerable.GetEnumerator()
    {
        return ((System.Collections.IEnumerable)_dict).GetEnumerator();
    }
}

显然,如果希望允许修改值,可以更改上面的this[]setter.

.net相关问答推荐

Docker失败文件找不到

将Visual Studio更新到v17.9.3后,IDE关闭,dotnet.exe命令报告致命错误.内部CLR错误.(0x80131506)

尽管有`disable`注释,但未 suppress Pylint语法错误

.NET restore/build在使用组织包的Github Action工作流中调用时获得401

使用.NET 8时无法识别运行标识符

获取Ef-Core集合的DeleteBehavior

使用 PEM 文件创建 DSA 签名

部署时如何控制红隼端口?

MassTransit RespondAsync 无法返回空值

Erlang 的让它崩溃的哲学 - 适用于其他地方吗?

如何使用 Moq 为不同的参数设置两次方法

如何在 WPF 应用程序中使用 App.config 文件?

大型 WCF Web 服务请求因 (400) HTTP 错误请求而失败

如何正确停止BackgroundWorker

在 .NET (C#) 中本地存储数据的最佳方式

检索字典值最佳实践

将 SignalR 2.0 .NET 客户端重新连接到服务器集线器的最佳实践

ADO.NET Entity Framework:更新向导不会添加表

C# 应用程序中的资源和嵌入式资源有什么区别?

LINQ 可以与 IEnumerable 一起使用吗?